State-Driven Animations with useState
What you'll learn: You'll learn how to trigger Framer Motion animations by changing React state, making your animations respond to user interactions.
The key insight with Framer Motion is that animations are declarative — you don't say "move this element 100px to the right," you say "the element's position should now be 100px to the right." When you change the animate prop based on React state, Framer Motion automatically animates the transition.
The Pattern
Instead of hardcoding the animate prop's values, derive them from useState:
import { motion } from 'framer-motion';
import { useState } from 'react';
function InteractiveBox() {
const [isExpanded, setIsExpanded] = useState(false);
return (
<motion.div
initial={{ scale: 1, opacity: 0.7 }}
animate={{
scale: isExpanded ? 1.5 : 1,
opacity: isExpanded ? 1 : 0.7
}}
transition={{ duration: 0.3 }}
onClick={() => setIsExpanded(!isExpanded)}
style={{ width: 100, height: 100, background: 'blue' }}
/>
);
}
When isExpanded changes from false to true, the animate prop's values change, and Framer Motion smoothly animates from the old values to the new ones.
Think of It Like a Puppet
Your state is the script, and Framer Motion is the puppeteer. You just change what the script says (isExpanded = true), and the puppeteer handles the smooth movement. You never manually calculate intermediate frames.
This works with any state trigger: button clicks, form inputs, API responses, timers — anything that updates state can drive animations.
Key Takeaway: By deriving the animate prop's values from useState, you make animations respond declaratively to state changes, letting Framer Motion handle all the interpolation automatically.