Course contentsShow
← Web Development
Lesson 2571 of 2,98246. Animation LibrariesFree lesson

useAnimation Hook for Imperative Control

Control animations imperatively with JavaScript logic using the useAnimation hook and controls.

useAnimation Hook for Imperative Control

What you'll learn: How to trigger and control Framer Motion animations programmatically using JavaScript logic instead of declarative props.


While Framer Motion's declarative approach (using animate, initial, and variants) covers most use cases, sometimes you need to start animations in response to events, API calls, or complex logic. That's where the useAnimation hook comes in.

Understanding Imperative vs Declarative

Until now, you've used declarative animations—you describe what should animate and React handles when. With useAnimation, you switch to imperative control: you explicitly tell animations when to start, stop, or change using JavaScript.

Think of it like the difference between setting a thermostat (declarative: "keep it at 70°") versus manually adjusting the temperature dial (imperative: "turn it up now").

How It Works

The useAnimation hook returns an animation controls object. You pass these controls to a motion component's animate prop, then call methods like controls.start() to trigger animations:

import { motion, useAnimation } from 'framer-motion';

function ImperativeExample() {
  const controls = useAnimation();

  const handleClick = () => {
    controls.start({
      x: 100,
      transition: { duration: 1 }
    });
  };

  return (
    <div>
      <motion.div animate={controls} style={{ width: 100, height: 100, background: 'blue' }} />
      <button onClick={handleClick}>Move Right</button>
    </div>
  );
}

When the button is clicked, controls.start() programmatically begins the animation. You can also call controls.stop() or chain multiple animations in sequence.

When to Use It

Use useAnimation when animations depend on:

  • User interactions beyond hover/tap
  • Data fetched from APIs
  • Complex conditional logic
  • Timing that doesn't align with component mounting

Key Takeaway: The useAnimation hook gives you JavaScript-driven control over Framer Motion animations, perfect for scenarios where declarative props aren't flexible enough.