Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 132 ยท Advanced Patterns

Animation and Transitions

Animate React the right way: state-driven CSS transitions, exit animations, requestAnimationFrame hooks, Activity, ViewTransition and prefers-reduced-motion.

Animation in React is mostly a question of who owns the clock. Sometimes the browser does: you change a CSS class and a transition interpolates between the old and the new look. Sometimes your code does: a requestAnimationFrame loop updates a number every frame. A library such as Framer Motion or React Spring runs the clock for you, and in newer React versions parts of this move into React itself.

The golden rule is to let the browser do as much as possible. CSS transitions and animations run off the main thread when they only change transform and opacity, so they stay smooth even when your JavaScript is busy. React's job is to say what state the UI is in; CSS describes how it gets there. This lesson goes from the simplest case (state-driven CSS) to the hard one (animating something that is leaving the page), then covers frame loops, Activity, ViewTransition, third-party libraries and accessibility for people who need less motion.

State-driven CSS transitions

A transition animates between two values of a CSS property. You do not animate in React; you just change a prop or class, and React updates the element. Because React keeps the same DOM node across renders, the browser sees the property change on an existing element and runs the transition.

A transition driven by state

Click the button and the box eases between two sizes, colours and corner radii. The state is a plain boolean; there is no animation code at all. Two details matter:

  • The element must stay mounted. If you write {isOpen && <Box />}, React creates a new node when the state flips and there is nothing to transition from. A node that appears has no previous value.
  • Prefer transform and opacity. Animating width and height forces layout every frame, which is fine for one small box but janky for big trees. transform: scale() and translate() can be handled by the compositor.

In a real project you would put the styles in a CSS file and toggle a class (className={isOpen ? 'panel panel-open' : 'panel'}); inline styles are used here only so each example is a single file. See Styling React Components.

Entering: animating a new element

A CSS @keyframes animation runs when an element is inserted, which is exactly what React does when a component mounts. So an enter animation needs no JavaScript at all.

Enter animation with keyframes

Press "Add note" a few times. Only the new note slides in; the existing ones do not replay their animation. That is the effect of the stable key: React keeps the older <li> nodes (their animation already finished) and inserts a fresh node for the new item. If you used the array index as key, every note would shift position and be reused, so you would see wrong content animate. This is another reason for the advice in Rendering Lists and Keys.

Exiting: the unmount problem

Exit animations are the hard part. When a component stops rendering, React removes its DOM node right away. There is no moment where the node is "leaving", so a CSS animation has nothing to run on.

The standard workaround is to keep the element mounted until the exit finishes. You track two things: whether the user wants it visible, and whether it is still in the DOM. A small hook handles this.

Exit animation with a delayed unmount

Click "Show toast", wait a moment, then hide it. The toast fades and slides down for 300 ms and only then disappears. The console logs "Toast removed from the DOM" three times in a full show-and-hide cycle: on the very first render (nothing mounted yet), on the render right after you click "Show" (the effect has not yet marked it as mounted), and once more when the exit has finished and the node is gone. The enter animation here is a CSS transition, so there is a subtlety: a freshly inserted node has no earlier style, so the first paint is already at opacity: 1. The toast therefore appears immediately and animates only on the way out. For a proper enter you combine this with the @keyframes approach from the previous section.

A fixed 300 ms timer must match your CSS duration, which is fragile. A more robust version listens for the onTransitionEnd or onAnimationEnd event and unmounts then. Libraries such as Motion's AnimatePresence and React Transition Group exist because this bookkeeping gets complicated with lists.

Animating with requestAnimationFrame

When the animation cannot be expressed in CSS (a number counting up, a physics simulation, a canvas), you run your own loop with requestAnimationFrame, which calls your function before each repaint, normally 60 times per second. Treat the loop as an external system, so it belongs in an effect with a cleanup (see Cleanup, Subscriptions and Timers).

A reusable hook takes the duration and returns progress from 0 to 1:

A useAnimatedValue hook

Press 1000: the number counts up quickly at first and slows near the end (the ease-out curve), the bar follows, and the console prints Animation finished at 1000. Three things make this loop safe:

  • Cleanup. The effect returns cancelAnimationFrame, so unmounting or changing target stops the old loop. Without it, an old loop would keep calling setValue after the component is gone.
  • Time, not frames. Progress comes from the timestamp, so the animation lasts 800 ms on a 60 Hz and on a 144 Hz display. Adding a fixed amount per frame makes speed depend on the monitor.
  • key={target} restarts the animation from zero by resetting the component. Without it, the hook would keep value from the previous target and jump (a gentler alternative is to store the starting value in a ref).

Calling setValue 60 times per second re-renders the component 60 times per second. That is fine for a small counter. For something heavy (a large list, a canvas with thousands of shapes), skip React state entirely: keep the value in a ref and write element.style.transform directly inside the loop, as an escape hatch (see Refs with useRef). Do not do this for anything React also renders; the two would fight over the same property.

Keeping state with Activity

Imagine a tabbed UI or a multi-step wizard. If you swap the panels with {tab === 'a' ? <A /> : <B />}, the hidden one is unmounted: its state, scroll position and typed input are lost. The opposite approach, CSS display: none, keeps the state but leaves all effects (timers, subscriptions) running while nobody can see the UI.

React 19.2 added the Activity component for exactly this middle path. With mode="hidden", React hides the children and keeps their state, but unmounts their effects (it runs the cleanup functions) and lowers the priority of their updates. When you switch back to mode="visible", the effects run again. The component also still exists in React's tree, so your typed text is still there.

Activity keeps state, pauses effects

Type something in the Email draft, click "Note", type there, then click "Email" again. Your Email text is still in the input. Meanwhile the console shows the effect life cycle, in this order: Email: effect started (first render), Email: effect cleaned up (you hid it), Note: effect started (it became visible for the first time), Note: effect cleaned up, and Email: effect started again. Notice that "Note" logged nothing at the start: a child that is hidden from its first render is rendered, but its effects do not run until it becomes visible. Hidden children get display: none, so they take no space. This also lets React pre-render screens the user is likely to open next at low priority.

Use Activity for tabs, steps, drawers and routes you want to restore instantly. Do not use it when hidden content is huge, because it stays in memory.

In React 19.3.1, which our editor loads, Activity is exported from react as shown. It first appeared in 19.2. Code that must support older versions needs a conditional import or a fallback.

View transitions

The browser has a native View Transitions API (document.startViewTransition) that takes a screenshot of the old state, applies a DOM change, and cross-fades or morphs to the new one. It is great for navigation and reordering because the browser does the measuring for you. Newer React builds export a ViewTransition component that triggers this for updates inside a transition (startTransition) and for Suspense reveals.

ViewTransition status check

In our editor's Chromium-based preview the console shows typeof ViewTransition: symbol and browser support: function, and the toggle runs without errors. The API is newer than the rest of this lesson, though: browser support for startViewTransition differs (check MDN's current table), and the React component has been evolving through the 19.x line, so verify the release notes of the version you ship before building on it. Treat it as progressive enhancement: without support the DOM simply updates with no animation.

Animation libraries

Reach for a library when you need things CSS handles badly:

Need Typical tool (read-only, not installed here)
Exit animations, layout animations, gestures, shared elements Motion (formerly Framer Motion): <motion.div animate={{ x: 100 }} />, AnimatePresence
Physics-based springs React Spring
Enter/exit classes for lists React Transition Group
Complex timelines, SVG GSAP (with its React hook)

A taste of the declarative style, as a read-only snippet that needs npm install motion:

JSX
import { motion, AnimatePresence } from 'motion/react';

function Toast({ isVisible }) {
  return (
    <AnimatePresence>
      {isVisible && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 10 }}
        >
          Saved successfully.
        </motion.div>
      )}
    </AnimatePresence>
  );
}

AnimatePresence is the library version of our useDelayedUnmount: it holds the element in the tree until the exit animation completes. Libraries cost bundle size (often tens of KB), so use CSS for hover effects, simple fades and toggles.

Motion (Framer Motion) hands-on

Motion (the library formerly called Framer Motion; import from motion/react) is the most popular animation library for React. Install it with npm install motion. Its idea is simple: swap an element for its motion. version and describe target values; the library animates between the current and the target values, using springs by default. Everything below is read-only, followed by a runnable stand-in for the mechanism.

The core props

JSX
// read-only
import { motion } from 'motion/react';

<motion.div
  initial={{ opacity: 0, y: 20 }}      // where it starts when it mounts
  animate={{ opacity: 1, y: 0 }}       // where it should be now (change it and it animates)
  exit={{ opacity: 0, y: -20 }}        // where it goes when it unmounts (needs AnimatePresence)
  transition={{ type: 'spring', stiffness: 300, damping: 24 }}
/>
  • animate is state-driven: put it in an expression such as animate={{ x: open ? 200 : 0 }} and the element glides whenever open changes. There is no timeline to manage.
  • transition picks the physics: a spring (stiffness, damping, bounce) or a tween (duration, ease).
  • Only transform and opacity are cheap to animate; x, y, scale and rotate are shortcuts for transforms.

Gestures: hover, tap, drag

JSX
// read-only
<motion.button
  whileHover={{ scale: 1.05 }}
  whileTap={{ scale: 0.95 }}
>
  Press me
</motion.button>

<motion.div drag dragConstraints={{ left: 0, right: 200, top: 0, bottom: 100 }} whileDrag={{ scale: 1.1 }} />

whileHover, whileTap, whileFocus, whileInView and whileDrag apply a target while the gesture lasts and return to the resting values afterwards. Compare with the manual pointer handling in Drag, Drop and Gestures.

Variants: named states that propagate

A variant is a named set of target values. Naming them lets a parent control children without passing props: when the parent's animate changes to "show", every child with matching variants animates too, and staggerChildren offsets them in time.

JSX
// read-only
const list = { hidden: {}, show: { transition: { staggerChildren: 0.08 } } };
const item = { hidden: { opacity: 0, y: 12 }, show: { opacity: 1, y: 0 } };

<motion.ul variants={list} initial="hidden" animate="show">
  {names.map((name) => (
    <motion.li key={name} variants={item}>{name}</motion.li>
  ))}
</motion.ul>

AnimatePresence: exit animations

React removes an unmounted element at once, so there is nothing left to animate. AnimatePresence keeps the element in the DOM until its exit animation finishes. Each direct child needs a stable key so the library can tell which one left.

JSX
// read-only
<AnimatePresence>
  {todos.map((todo) => (
    <motion.li
      key={todo.id}
      layout
      initial={{ opacity: 0, height: 0 }}
      animate={{ opacity: 1, height: 'auto' }}
      exit={{ opacity: 0, height: 0 }}
    >
      {todo.text}
    </motion.li>
  ))}
</AnimatePresence>

Layout animations

Adding the layout prop makes an element animate between layouts: when a sibling is removed or a list is reordered, the others slide smoothly into their new positions, even though nothing in your code mentions positions. This is the feature that is almost impossible with plain CSS. layoutId goes further: two elements with the same layoutId (for example a tab underline) morph into each other across renders.

Reduced motion

Wrap the app in <MotionConfig reducedMotion="user"> and the library will disable transform and layout animations when the operating system asks for reduced motion, while keeping opacity changes. You can also read the preference with useReducedMotion(). See the next section on respecting the setting.

Runnable stand-in: enter and exit with the Web Animations API

The real Motion cannot load in the editor. This stand-in keeps an element mounted until its exit animation has finished, which is the core trick of AnimatePresence, using the browser's built-in Web Animations API. It is a teaching sketch, not a replacement.

Stand-in: a presence component with enter and exit animations

Remove an item: it fades up and out, and only then leaves the DOM. The real library adds layout animation, so the siblings also slide into place. Use Motion when you need that, and CSS for everything simpler.

Respect prefers-reduced-motion

Some people get dizzy, nauseous or distracted by large motion. Operating systems offer a "reduce motion" setting, which browsers expose as the CSS media query prefers-reduced-motion: reduce. Honour it: replace big movements with fades or instant changes, and never autoplay long animations. In CSS:

CSS
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

In JavaScript (for requestAnimationFrame loops, or to skip a library animation) read the same query with matchMedia and subscribe to changes. useSyncExternalStore is the right hook for this, and External Stores and useSyncExternalStore explains why.

A usePrefersReducedMotion hook

By default the page prints false and the square spins. With the OS setting enabled the hook returns true and the animation is removed, without any change in component code. The third argument (() => false) is the value used during server rendering, where window does not exist.

Performance and design notes

  • Animate transform and opacity; avoid animating width, height, top and left on large areas.
  • Do not drive 60 fps animations through state of a component that renders a lot of children. Isolate the animated part in its own small component, or write to the DOM through a ref.
  • will-change can help, but each use costs memory. Add it only for elements you measured.
  • Keep durations short: 150-300 ms for small UI changes, up to 500 ms for large panels. Ease-out feels natural for entering, ease-in for leaving.
  • Animation must never be the only carrier of information, and nothing important should move so fast that it cannot be read.
  • Test in StrictMode: effects run twice in development, so a start-animation effect must clean up properly (see Effects with useEffect).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does {isOpen && <Box />} give you no enter transition with a CSS transition?

    A transition interpolates an existing element's property change. A node created at that moment starts with its final style. Keep the node mounted and change its style, or use a keyframes animation for entering.
  2. 2. What is the main difficulty of exit animations in React?

    Unmounting removes the node at once, so nothing remains to animate. The usual fix is to keep the element mounted until the animation ends, as AnimatePresence or a delayed-unmount hook does.
  3. 3. Why should a requestAnimationFrame hook compute progress from timestamps?

    If you add a fixed amount per frame, speed depends on the display refresh rate. Using the elapsed time makes the duration the same everywhere. You still need the effect cleanup to cancel the loop.
  4. 4. What happens to a child inside <Activity mode="hidden">?

    Activity preserves state while hidden, but runs effect cleanups and lowers the priority of updates. When it becomes visible again the effects are set up again.
  5. 5. How should you honour a user's reduced-motion setting from JavaScript?

    The media query is the standard signal. useSyncExternalStore with matchMedia reads and subscribes to it safely; CSS can use the same query directly.

Summary

  • Let the browser animate: change state or class and let CSS transition or @keyframes do the work, preferring transform and opacity.
  • A transition needs a node that stays mounted; an enter animation can be a keyframes animation that runs on insertion; stable keys prevent old list items from replaying.
  • Exit animations need the element kept mounted until the animation ends (a delayed unmount, onAnimationEnd, or AnimatePresence).
  • For custom frame loops use requestAnimationFrame inside an effect, compute progress from time and always cancel in the cleanup.
  • Activity hides UI while preserving state and pausing its effects; ViewTransition wraps the browser's View Transitions API and should be treated as progressive enhancement.
  • Always respect prefers-reduced-motion, and keep animations short and non-essential.

Next: Drag and Drop, Gestures and Pointer Events