Mastering Framer Motion: The Ultimate Guide to Animating React Apps
Framer Motion is a production-ready motion library for React that makes creating fluid, declarative animations remarkably simple. Whether you’re building a landing page with subtle micro-interactions or a complex UI with shared layout animations and gesture-driven transitions, Framer Motion provides a powerful yet intuitive API. Unlike CSS animations or older JavaScript animation libraries, Framer Motion integrates seamlessly with React’s component model, allowing you to animate props, variants, and even layout changes without touching the DOM directly. In this comprehensive tutorial, we will cover everything you need to get started, from installation to advanced patterns like AnimatePresence, layout animations, and scroll-triggered effects. By the end of this guide, you will be able to add professional-grade animations to any React project with confidence.
The library was built by the team behind Framer, a design tool for prototyping, and it has become the go-to solution for React animation. Its core philosophy is declarative animation—you define what the animation should look like (e.g., start and end states) and Framer Motion handles the interpolation, easing, and performance optimizations automatically. Under the hood, it leverages the Web Animations API and requestAnimationFrame for smooth 60fps animations, but you never need to worry about the implementation details. Instead, you work with familiar React concepts like motion components, animate props, and variants. This guide assumes you have a basic understanding of React (components, state, props, hooks) but no prior experience with animation libraries. Each step will be explained thoroughly with code examples, best practices, and common pitfalls to avoid.
Setting Up Framer Motion in Your Project
Before we can start animating, we need to install the library. Framer Motion is available as an npm package and works with any React project built with Create React App, Vite, Next.js, or even a custom Webpack setup. The installation process is straightforward: open your terminal in the project root directory and run npm install framer-motion or yarn add framer-motion. Once installed, you can import the necessary components and hooks. The two primary exports you’ll use are motion (a factory for creating animated HTML/SVG elements) and AnimatePresence (for entering and exiting animations). For more advanced use cases, you may also import useAnimation, useInView, useCycle, and other utilities. It’s important to note that Framer Motion is tree-shakable, so you only bundle the parts you actually use. For example, if you only need basic animations, importing motion is sufficient; you don’t need to import the entire library. In this tutorial, we’ll assume you have React 16.8 or later (hooks support) and a modern browser. After installation, create a new component file (e.g., AnimationDemo.jsx) and start by adding the import statement: import { motion } from 'framer-motion';. Now you’re ready to build your first animation.
Step-by-Step Guide to Using Framer Motion
Step 1: Creating Your First Motion Component and Applying the animate Prop
The most fundamental concept in Framer Motion is the motion component. Instead of using standard HTML elements like <div> or <span>, you replace them with motion.div or motion.span. These components behave exactly like their native counterparts, but they expose animation-related props. The simplest animation is achieved by using the animate prop, which defines the final state of the element after the animation. For example, to make a box move from its current position to 100 pixels to the right and simultaneously change its opacity from 0 to 1, you would write: <motion.div animate={{ x: 100, opacity: 1 }} />. By default, the element will animate from its initial CSS state (if no initial prop is set) to the animate state. The transition between these states is automatically tweened using default easing (ease-in-out) and a duration of 0.3 seconds. However, you can customize the timing, easing, and delay using a transition prop. For instance, <motion.div animate={{ x: 100 }} transition={{ duration: 1, ease: "easeOut" }} /> will take one second to complete. It’s important to understand that the animate prop can also be used to chain multiple animations over time by using keyframes. Simply pass an array of values to any animatable property: animate={{ x: [0, 100, 50] }} will move the element from its current x (0) to 100, then back to 50, with equal duration segments per keyframe (unless you specify a transition with times). Try creating a simple colored box and watch it slide to the right when the component mounts.
Step 2: Defining Initial States and Using Variants
Often you want the element to start off-screen or invisible and then animate into view. The initial prop allows you to set the starting state of the animation. Combine it with the animate prop to create a mount animation. For example: <motion.div initial={{ opacity: 0, scale: 0.5 }} animate={{ opacity: 1, scale: 1 }} />. This will cause the element to fade in and grow from half its size. While this approach works for simple cases, Framer Motion introduces a more powerful concept called variants. Variants allow you to define named animation states and orchestrate them across multiple components or even children. Instead of writing initial and animate objects inline, you define a variants object with keys like “hidden”, “visible”, “exit”, etc. Each variant can contain any animatable properties and a transition object. Then you pass the initial and whileInView (or animate) props with the variant name. For example:
const boxVariants = {
hidden: { opacity: 0, x: -100 },
visible: { opacity: 1, x: 0, transition: { duration: 0.5 } }
};
// Usage:
<motion.div variants={boxVariants} initial="hidden" animate="visible" />
Variants are especially useful when you want to stagger animations among children. By adding transition={{ staggerChildren: 0.1 }} to the parent’s visible variant, each child element will animate one after another with a 100ms delay. This creates a cascading effect that is both elegant and easy to implement. Variants also support when: "beforeChildren" or afterChildren, giving you fine control over the order of animation. Mastering variants is the key to building complex, coordinated animations without messy setTimeout calls.
Step 3: Adding Gesture Animations (Hover, Tap, Drag)
Interactive animations respond to user input. Framer Motion provides several gesture props that work out of the box: whileHover, whileTap, whileFocus, whileInView, and whileDrag. Each of these props accepts an object of animatable properties (similar to animate) that are activated when the corresponding event occurs. For example, to make a button scale up slightly when hovered and press down when clicked, you can write: <motion.button whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>Click Me</motion.button>. The transitions for these gestures can be customized using the transition prop placed directly on the motion component or nested inside each gesture object. For drag, you need to set the drag prop to "x", "y", or true for both axes, and then optionally use dragConstraints to limit the draggable area. A draggable card that snaps back to its original position after release can be created with <motion.div drag="x" dragConstraints={{ left: -100, right: 100 }} whileDrag={{ scale: 1.2 }} />. Gesture animations are highly optimized and respect the layout prop as well. They are the perfect way to add polish to UI elements like buttons, cards, and modals.
Step 4: Managing Enter and Exit Animations with AnimatePresence
In React, when a component is conditionally rendered using {show && <Component />}, it appears or disappears instantly. To animate the mounting and unmounting of components, you need to wrap them with AnimatePresence. This component detects when children are added or removed and applies the defined exit animations. To use it, import AnimatePresence from framer-motion and wrap the conditional block. Then, on the motion child, add an exit prop that defines its final state before removal. For example:
import { AnimatePresence, motion } from 'framer-motion';
function Modal({ isOpen }) {
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 20 }}
key="modal"
>
Content here
</motion.div>
)}
</AnimatePresence>
);
}
Important: AnimatePresence requires each child to have a unique key prop to track entering/exiting elements. Without it, the library cannot distinguish between components and the exit animation may not work. You can also use mode prop on AnimatePresence to control how enter and exit animations interact. The default mode "sync" tries to animate both simultaneously. Use mode="wait" if you want the exiting element to finish its animation before the entering element starts, which is useful for page transitions. Additionally, AnimatePresence supports initial={false} to skip the initial mount animation if the component is already present when the app loads. This pattern is essential for creating smooth transitions between different views in a tabbed interface or a modal.
Step 5: Layout Animations and Shared Layout IDs
One of the most powerful features of Framer Motion is the ability to animate changes in an element’s size, position, or layout automatically. When two elements share the same layoutId, Framer Motion will smoothly animate the transformation from one to the other as they swap positions or are rearranged. This is commonly used for list reordering, accordion menus, and page transitions where a thumbnail expands into a full-screen image. To enable layout animation on any motion component, simply add the layout prop. For instance, if you have a <motion.div layout> inside a flex container, and you change its order or visibility, the element will animate to its new position. You can also combine layout with initial and animate for entrance animations. For shared layout animations across different components (like a button that becomes a full card), assign the same layoutId string to both elements. When one is removed and the other appears, Framer Motion will interpolate the bounding box, creating a seamless morphing effect. This is perfect for routing transitions in Next.js or React Router. You can even animate layout changes conditionally using layoutDependency prop. However, be aware that layout animations require the parent element to have position: relative or a stacking context. Also, for performance, you can set layout="position" to only animate position changes (ignoring size) or layout="size" for only size. Using layout animations wisely can drastically improve the perceived performance and polish of your application.
Step 6: Scroll-Triggered Animations Using useInView and whileInView
Animating elements as they scroll into the viewport is a staple of modern web design. Framer Motion provides two seamless ways to achieve this: the whileInView prop (a variant of gesture props) and the useInView hook for more control. The simplest approach is to add whileInView to a motion component and optionally define an initial state. For example, <motion.div initial={{ opacity: 0, y: 50 }} whileInView={{ opacity: 1, y: 0 }} /> will fade and slide up when the element comes into the viewport. You can also set viewport={{ once: true }} to ensure the animation only fires once (otherwise it will re-trigger every time the element enters the viewport). For more complex scenarios, the useInView hook returns a ref and a boolean indicating whether the element is visible. You can then use that boolean to drive animations via the animate prop or a separate useAnimation controller. Example:
const ref = useRef(null);
const isInView = useInView(ref, { once: true });
return <motion.div ref={ref} animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 50 }} />;
The useInView hook is especially useful when you want to chain multiple animations or conditionally enable/disable other interactions. You can also configure the threshold (how much of the element must be visible) and root margin using the options object. Scroll-triggered animations are ideal for revealing content gradually as the user scrolls down a landing page, creating a sense of discovery. Always remember to use willChange (or let Framer Motion handle it) to optimize performance for elements that animate heavily. Combine scroll animations with layout animations for truly interactive storytelling.
Tips and Best Practices for Framer Motion
Tip 1: Optimize Performance by Limiting Animated Properties and Using willChange
While Framer Motion is highly optimized, animating too many properties simultaneously or animating layout-heavy properties like width and height can cause repaints and jank. A general rule is to prefer CSS transforms (like scale, translate, rotate) over width, height, or top/left because transforms are offloaded to the GPU. Framer Motion automatically promotes elements to a new compositing layer when using transforms, but you can further help by setting style={{ willChange: 'transform' }} on motion components that animate frequently. Additionally, avoid animating height: 'auto' (use layout animations instead with explicit start/end heights). For massive list animations, consider using AnimatePresence with positionTransition or layout sparingly. The useReducedMotion hook is also crucial for accessibility—it respects the user’s system preference for reduced motion and allows you to disable or simplify animations accordingly. Always wrap your animation logic with this hook to create an inclusive experience.
Tip 2: Leverage Variants and staggerChildren for Coordinated Animations
Writing inline animation objects for dozens of list items is not only tedious but also difficult to maintain. Variants solve this by decoupling the animation definition from the component tree. Define a parent variant with staggerChildren and optionally delayChildren to control the sequence. For example, a container for a list might have visible: { transition: { staggerChildren: 0.1 } }, and each child defines its own hidden and visible states. This creates a polished cascade effect with minimal code. Variants are also composable—you can nest variants by simply passing them down via the variants prop on each motion element. When combined with AnimatePresence, you can even stagger exit animations. Best practice: keep variant definitions in a separate constants file or inside the component to avoid prop drilling. Use descriptive names like cardAnimation or fadeSlideLeft for readability.
Tip 3: Use useAnimation for Imperative Control and Complex Sequences
Sometimes you need to start an animation based on a user action that is not a direct gesture (e.g., after a fetch completes, or when a state changes). The useAnimation hook returns a control object with start and stop methods. You attach this control to a motion component via the animate prop (yes, the same prop can accept either a target object or a control). Then you can call controls.start({ x: 100 }) imperatively. For sequences, you can chain multiple start calls using async/await or promises. For instance:
const controls = useAnimation();
const runSequence = async () => {
await controls.start({ scale: 1.5 });
await controls.start({ x: 200 });
controls.start({ rotate: 360 });
};
This gives you fine-grained control over timing and can be combined with useCycle to toggle between multiple states. However, avoid overusing imperative animations—prefer declarative props like animate and whileInView when possible, as they are easier to debug and maintain.
Frequently Asked Questions (FAQ)
Q1: Why is my Framer Motion animation not working at all?
The most common reasons include: forgetting to import motion from framer-motion (check your import statement), using a standard HTML element like <div> instead of <motion.div>, or the element not having an initial state different from its animate state. Also ensure that the component is mounted in the React tree and that you haven’t accidentally set a CSS transform property that conflicts with Framer Motion’s transforms (they will override each other). Check your browser console for errors; sometimes a missing closing tag or a typo in a property name (e.g., opacity spelled as opacity is fine, but opacitiy is not) can break the animation. Another frequent issue is using transition inside the animate object incorrectly—it should be a separate prop or inside the variant object, not nested inside the target values. Finally, if you’re using AnimatePresence, ensure each child has a unique key prop.
Q2: How do I animate on scroll using Framer Motion?
You have two main options: use the whileInView prop (the easiest) or the useInView hook (more control). For whileInView, simply add it to a motion component along with an initial state and optionally set viewport={{ once: true }} to prevent re-triggering. For custom scroll-based animations that depend on the scroll position (e.g., parallax), you can use the useScroll hook along with useTransform to create values that map scroll offset to animation values. For example:
const { scrollYProgress } = useScroll();
const scale = useTransform(scrollYProgress, [0, 1], [0.5, 1]);
return <motion.div style={{ scale }} />;
This allows you to tie animations directly to the scroll progress, enabling advanced effects like fading a header as you scroll down. Always use useTransform instead of manually updating styles in a scroll event listener for performance reasons.
Q3: Can I animate SVG elements with Framer Motion?
Absolutely. Framer Motion supports all standard SVG elements via the motion factory, e.g., motion.circle, motion.path, motion.rect, etc. You can animate SVG-specific properties like pathLength, strokeDashoffset, fill, and stroke. The pathLength animation is especially popular for drawing strokes. For example, to animate a line drawing effect, set pathLength: 0 in initial and pathLength: 1 in animate. You can also animate cx, cy, r, width, height, etc. Note that SVG coordinates are not transformed by CSS transforms the same way as HTML elements, but Framer Motion handles the translation correctly. For complex SVG animations, using variants and staggerChildren works just as well.
Q4: How do I chain multiple animations in sequence?
There are several approaches. The simplest is to use the transition prop’s delay property to offset each animation. Alternatively, you can use keyframes in the animate prop: animate={{ x: [0, 100, 200], opacity: [1, 0.5, 1] }} will run a sequence through the arrays. For more complex chaining, use the useAnimation hook with async/await as shown in Tip 3 above. If you’re using variants, you can set transition={{ delay: 0.5 }} on a child variant to start after the parent. The AnimatePresence with mode="wait" also naturally chains the exit of one component before the enter of another. For chaining multiple unrelated elements, consider using the animationSequence API from framer-motion‘s older version (v6) or use custom logic with state changes. The key is to avoid nesting setTimeout calls; rely on Framer Motion’s built-in sequencing mechanisms.
Q5: How do I animate an element’s height from 0 to auto?
Animating to auto height is tricky because the browser cannot interpolate between a fixed value and auto. The recommended approach is to use the layout prop. Wrap the content inside a <motion.div layout>. When you toggle visibility or change the content’s size, the parent will animate its height smoothly. However, if you need a true collapse/expand animation (like an accordion), you can use the AnimatePresence with a child that has a fixed height in animate (by measuring the clientHeight) or use the height: "auto" trick by setting the initial value to 0, then in animate set a known height (e.g., height: 200). But that requires knowing the exact height. A better solution is to measure the child’s height with a ref and use useState to store it, then animate to that value. Framer Motion also provides the overflow: "hidden" style automatically when animating height with layout. For a pure CSS-free approach, set height: 0 initially, then inside animate use height: "auto"? That still won’t interpolate. So stick with layout animations—they are the most reliable and performant.
Q6: Can I use Framer Motion with CSS frameworks like Tailwind or Styled Components?
Yes, absolutely. Framer Motion works with any styling solution. You can combine motion components with Tailwind classes by passing tailwind class names to the className prop. For example: <motion.div className="flex items-center" animate={{ x: 100 }} />. With Styled Components, you can create a styled motion component like const StyledBox = styled(motion.div)`` and use it normally. However, be cautious: some CSS properties may conflict with Framer Motion’s animated values (e.g., setting transform in a class will be overridden by the animation). The library inherits existing styles and animates from them, but if a CSS rule has higher specificity, it might overwrite the animation’s final state. The solution is to use the style prop for values that you intend to animate dynamic. Also, when using Tailwind’s hover: utilities, they may conflict with whileHover. In that case, rely on Framer Motion’s gesture props instead of Tailwind hover classes.
Conclusion
Framer Motion is an extraordinarily powerful library that democratizes animation in React. From simple fades and slides to complex coordinate-based, gesture-driven, and layout-shifting animations, it provides a clean declarative API that integrates with the component lifecycle. In this guide, we’ve covered the essentials: setting up motion components, using the animate prop, leveraging variants for complex sequencing, adding gesture interactivity, managing mount/unmount animations with AnimatePresence, and creating scroll-triggered effects. We also discussed performance best practices, the importance of accessibility with useReducedMotion, and answered common questions about SVG animations, chaining, and auto height. Remember that the key to mastering Framer Motion is to think declaratively: define states (initial, animate, exit, hover, etc.) and let the library handle the interpolation. Experiment with the different props, use the official documentation extensively, and don’t be afraid to combine multiple features like layout + variants + scroll animations. As you build more complex UIs, you’ll discover that Framer Motion not only saves time but also encourages a mindset of fluid, interactive design. Start small, perhaps by animating a button or a modal, then gradually adopt layout animations for page transitions. With practice, you’ll be able to create animations that feel natural and elevate the user experience of any React application.
Reference Tables
| Prop | Description | Example Values |
|---|---|---|
initial |
The starting state of the component before the animation. Can be an object or a variant name. |
{{ opacity: 0 }} or "hidden" |
animate |
The target state to animate to. Can be an object, variant name, or animation controls. |
{{ x: 100 }} or "visible" |
exit |
The state to animate to when the component is removed from the tree (used with AnimatePresence). |
{{ opacity: 0 }} |
transition |
Configures duration, easing, delay, and orchestration for the animation. | {{ duration: 0.5, ease: "easeOut" }} |
variants |
An object containing named animation states. Allows orchestration across children. | { hidden: {...}, visible: {...} } |
layout |
Enables automatic animation of layout changes (position, size). | true or "position" or "size" |
layoutId |
Shared identifier between different components for cross-component layout animation. | A unique string like "card-1" |
| Prop | When It Triggers | Common Use Case |
|---|---|---|
whileHover |
User hovers over the element (mouse pointer enters). | Scale up a button on hover. |
whileTap |
User presses (mousedown / touchstart) on the element. | Create a press-down effect. |
whileFocus |