Skip to content

Lesson 23 of 37Modern React

Animation and View Transitions

Pick between CSS, Motion and React's ViewTransition, animate enters, exits, reorders and shared elements, and keep motion fast and accessible.

16 min read0/4 questions

The design review for your product grid comes back with three notes. Filtering should not make cards jump into place. Opening a product should feel like the card grows into the detail page. Going back should slide the other way. Each sounds small, but React fights you on all three: a removed element leaves the DOM at once, so there is nothing left to animate, and the card and the detail page are different components in different parts of the tree. This lesson gives you the three tools teams actually use, when each one fits, and how React 19.3's <ViewTransition> handles the cases that used to need a library.

Three tools, three jobs

You already know CSS transitions and keyframes from Transitions and Animations in the HTML and CSS track. In React they remain the first choice, because they cost nothing and run off the main thread when you animate transform and opacity. The question is what CSS cannot do on its own.

NeedCSS transitions and keyframesMotion (motion/react)<ViewTransition>
Hover, focus, open and closed statesBest fitWorks, but overkillNot for this
Enter animation@starting-style or a keyframeinitial and animateenter
Exit animationNot possible after unmountAnimatePresenceexit
List reorderHard (you would measure by hand)layout propDefault update morph
Element morphing across components or pagesNolayoutId, within one React treename, across anything React renders
Gestures, drag, springs, scroll-linkedPartial (scroll-driven animations)Best fitNo
CostZero JavaScriptA real dependency, check the bundleBuilt into React and the browser

Motion is the library formerly called Framer Motion. The package is motion and the React import is motion/react. It animates in JavaScript, which means springs, interruptible gestures and drag feel natural, at the cost of bundle size and main-thread work.

<ViewTransition> wraps the browser's View Transitions API. The browser takes a picture of the page before an update and after it, then animates between the two pictures with CSS. Because it animates snapshots, not live React components, it can morph a card in a grid into a hero image on another screen, even though React unmounted one and mounted the other.

A sensible default at work: CSS for component states, <ViewTransition> for anything that changes what is on screen (navigations, filtering, list changes, loading states), and Motion only where you need gestures or physics.

Why exits are hard in React

When a component stops rendering, React removes its DOM node during the commit. A CSS transition needs the element to exist while it animates, so there is nothing to fade out. Libraries solve this by keeping the element around: Motion's AnimatePresence holds a child in the DOM after React has stopped rendering it, plays its exit animation, then lets it go.

Toast.tsx (Motion)
import { AnimatePresence, motion } from "motion/react";
 
export function Toast({ message }: { message: string | null }) {
  return (
    <AnimatePresence>
      {message && (
        <motion.div
          key={message}
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 8 }}
        >
          {message}
        </motion.div>
      )}
    </AnimatePresence>
  );
}

View transitions solve it differently. The browser captured the old element as an image before the DOM changed, so the "exit" is an animation of that image. The real node is already gone.

How a view transition works

The browser API is document.startViewTransition(update). Here is what happens when it runs, which is exactly what React does for you when a <ViewTransition> activates.

One view transition
ReactBrowserPseudo layerstartViewTransitionsnapshot oldrun the updatesnapshot newbuild ::view-transitionanimatefinished

A transition is about to commit. React asks the browser to start a view transition and hands it the DOM update to perform.

1/7
The pseudo-element tree during a transition
::view-transitionoverlay on top of the page::view-transition-old(root)picture before::view-transition-new(root)picture after::view-transition-image-pair(root)::view-transition-group(root)the whole page, cross-fades by default::view-transition-old(card-42)::view-transition-new(card-42)::view-transition-image-pair(card-42)::view-transition-group(card-42)one group per named elementroot

The overlay sits above the page for the length of the animation.

1/3

<ViewTransition> in React

Wrap the part of the UI that should animate:

import { ViewTransition } from "react";
 
<ViewTransition>
  <ProductGrid products={visible} />
</ViewTransition>

The rule that surprises everyone: a <ViewTransition> only animates updates that happen inside a transition. That means updates in startTransition or an Action, a value from useDeferredValue, or a Suspense boundary revealing its content. A plain setState from a click is an urgent update, and React will not make the user wait for an animation before showing it. If nothing animates, the first thing to check is whether the update was wrapped.

React decides which of four kinds of animation a boundary gets:

  • enter: the <ViewTransition> was inserted in this transition.
  • exit: it was removed.
  • update: something inside it changed, or it moved (a list reorder).
  • share: a named boundary was removed in one place and a boundary with the same name was added somewhere else.

Each is a prop: enter, exit, update, share, plus default for the rest. The value is a CSS class name React attaches to the snapshot (as a view-transition-class), "auto" for the browser's default cross-fade, or "none" to switch that kind off. You then style the pseudo-elements by class.

For enter and exit to fire, the <ViewTransition> has to be the outermost thing that appears or disappears. {open && <ViewTransition><Panel /></ViewTransition>} gets an enter. {open && <div><ViewTransition>...</ViewTransition></div>} does not, because the div is what was inserted.

Try the list below. Shuffle reorders (update), Add and Remove insert and delete (enter and exit). Untick the checkbox to run the same updates as plain setState and see them snap.

ReactAnimatedList.tsx
import { startTransition, useState, ViewTransition } from "react"; const css = ` ::view-transition-new(.slide-in) { animation: 260ms ease-out both slide-in; } ::view-transition-old(.slide-out) { animation: 200ms ease-in both slide-out; } @keyframes slide-in { from { opacity: 0; transform: translateX(-24px); } } @keyframes slide-out { to { opacity: 0; transform: translateX(24px); } } @media (prefers-reduced-motion: reduce) { ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; } } .item { padding: 8px 12px; margin: 6px 0; border: 1px solid #ccc; max-width: 240px; }`; let nextId = 4; export default function App() { const [items, setItems] = useState([1, 2, 3]); const [isAnimated, setIsAnimated] = useState(true); function update(fn: (prev: number[]) => number[]) { if (isAnimated) startTransition(() => setItems(fn)); else setItems(fn); } return ( <div> <style>{css}</style> <label> <input type="checkbox" checked={isAnimated} onChange={(e) => setIsAnimated(e.target.checked)} /> Use startTransition </label> <div style={{ display: "flex", gap: 8, margin: "8px 0" }}> <button onClick={() => update((p) => [...p].sort(() => Math.random() - 0.5))}>Shuffle</button> <button onClick={() => update((p) => [nextId++, ...p])}>Add</button> <button onClick={() => update((p) => p.slice(0, -1))}>Remove last</button> </div> {items.map((id) => ( <ViewTransition key={id} enter="slide-in" exit="slide-out"> <div className="item">Item {id}</div> </ViewTransition> ))} </div> );}

Notice that the key sits on the <ViewTransition>, not on the div. The boundary is the thing in the list, so it needs the identity. React gives each one an automatic view-transition-name, which is how the browser knows item 3 at the bottom is the same item 3 now at the top, and the default update animation moves its group there.

Quick check
A filter chip calls setFilter(next) directly in its onClick. The grid is wrapped in <ViewTransition>, but nothing animates. What is the most likely fix?
Need a nudge? A hint rules out a wrong answer.

Shared elements with name

Giving a boundary a name turns it into a shared element. When a boundary with that name leaves one part of the tree and another with the same name appears elsewhere in the same transition, React pairs them and the browser morphs the old box into the new one. Two rules: the name must be unique among what is mounted at any moment, and both sides must change in the same transition.

Click a swatch. The grid and the detail view are completely different components, yet the square grows into place.

ReactSharedElement.tsx
import { startTransition, useState, ViewTransition } from "react"; const COLORS = [ { id: "sky", hex: "#38bdf8" }, { id: "lime", hex: "#a3e635" }, { id: "rose", hex: "#fb7185" }, { id: "amber", hex: "#fbbf24" },]; function Grid({ onOpen }: { onOpen: (id: string) => void }) { return ( <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 56px)", gap: 8 }}> {COLORS.map((c) => ( <ViewTransition key={c.id} name={`swatch-${c.id}`}> <button aria-label={c.id} onClick={() => onOpen(c.id)} style={{ width: 56, height: 56, background: c.hex, border: 0, borderRadius: 0 }} /> </ViewTransition> ))} </div> );} function Detail({ id, onBack }: { id: string; onBack: () => void }) { const color = COLORS.find((c) => c.id === id)!; return ( <div> <button onClick={onBack}>Back</button> <ViewTransition name={`swatch-${id}`}> <div style={{ width: 220, height: 160, background: color.hex, marginTop: 8 }} /> </ViewTransition> <p>{color.id}: {color.hex}</p> </div> );} export default function App() { const [openId, setOpenId] = useState<string | null>(null); const go = (id: string | null) => startTransition(() => setOpenId(id)); return openId ? <Detail id={openId} onBack={() => go(null)} /> : <Grid onOpen={go} />;}

In a real app the same pattern gives you the card-to-product-page morph. In Next.js, router navigations already run as transitions, so a <ViewTransition name={"product-" + id}> on the card and on the product page hero is enough once the framework's view transition support is switched on. At the time of writing that is a flag in next.config, so check the Next.js docs for your version.

Direction with transition types

"Back should slide the other way" needs the animation to know why the transition happened. addTransitionType tags the current transition, and the animation props accept an object keyed by type:

import { addTransitionType, startTransition, ViewTransition } from "react";
 
function goTo(step: number, current: number) {
  startTransition(() => {
    addTransitionType(step > current ? "forward" : "back");
    setStep(step);
  });
}
 
<ViewTransition
  key={step}
  enter={{ forward: "slide-from-right", back: "slide-from-left", default: "none" }}
  exit={{ forward: "slide-to-left", back: "slide-to-right", default: "none" }}
>
  <WizardStep step={step} />
</ViewTransition>

Changing the key makes React treat each step as a new boundary, so the old one exits and the new one enters. If no key matches the transition's types, React uses default.

Predict the outputReact

Which view transition class does the entering step get?

startTransition(() => {
addTransitionType("forward");
setStep(3);
});

<ViewTransition
key={step}
enter={{ back: "slide-from-left", default: "fade" }}
>
<WizardStep step={step} />
</ViewTransition>
Need a nudge? Hints walk you through it.

Animating Suspense reveals

A Suspense boundary swapping its fallback for content is one of the triggers. Wrap the whole boundary and the swap cross-fades:

<ViewTransition>
  <Suspense fallback={<ReviewsSkeleton />}>
    <Reviews productId={id} />
  </Suspense>
</ViewTransition>

For more control, put a boundary on each side. The fallback gets an exit, the content gets an enter, and you can slide the content up as the skeleton fades:

<Suspense
  fallback={
    <ViewTransition exit="fade-out">
      <ReviewsSkeleton />
    </ViewTransition>
  }
>
  <ViewTransition enter="slide-up">
    <Reviews productId={id} />
  </ViewTransition>
</Suspense>

React also throttles Suspense reveals that land close together, so a page full of boundaries tends to reveal in a few batches rather than a dozen separate animations. Design for that: group related content under one boundary.

Speed, motion sickness and browser support

The performance rules from Transitions and Animations still apply, and matter more here:

  • Animate transform and opacity. View transitions do this by design. Motion does it when you animate x, y, scale and opacity. Animating width, height or top forces layout every frame.
  • Keep them short. 150 to 300 ms for UI changes. While a view transition runs, the pseudo layer sits over the page, and a long animation makes the app feel slower, not smoother.
  • Respect prefers-reduced-motion. For view transitions, the media query in the demo above switches off every pseudo-element animation. In Motion, <MotionConfig reducedMotion="user"> at the root makes transform animations respect the setting, and the useReducedMotion() hook lets you choose a simpler animation. Reduced motion means less movement, not always none: a short fade is usually fine.
  • Nothing important should depend on the animation. Content must be correct and usable with motion off.

View transitions for same-page updates are supported in current Chromium browsers and Safari, and Firefox shipped them more recently. Where the API is missing, React simply applies the update without animating, so it is a safe progressive enhancement. Check current support on caniuse before promising a designer an effect on every browser.

Fragment refs: grouping without a wrapper

Animation code often needs to observe a group of elements, such as fading items in as they scroll into view, or to move focus into a group that just appeared. Refs showed the fix: put the ref on a Fragment instead of a wrapper div that breaks grid and flex layouts. The FragmentInstance you get acts on the fragment's first-level DOM children: observeUsing(observer) and unobserveUsing, addEventListener, focus() and focusLast(), getClientRects() and a few more.

RevealOnScroll.tsx
import { Fragment, useEffect, useRef, type FragmentInstance } from "react";
 
export function RevealOnScroll({ children }: { children: React.ReactNode }) {
  const ref = useRef<FragmentInstance>(null);
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      for (const e of entries) if (e.isIntersecting) e.target.classList.add("is-visible");
    });
    const fragment = ref.current!;
    fragment.observeUsing(observer);
    return () => fragment.unobserveUsing(observer);
  }, []);
  return <Fragment ref={ref}>{children}</Fragment>;
}

Here the fragment listens for clicks on all its buttons and focuses the first one, with no extra element in the DOM.

ReactFragmentRef.tsx
import { Fragment, useEffect, useRef, useState, type FragmentInstance } from "react"; export default function App() { const group = useRef<FragmentInstance>(null); const [clicks, setClicks] = useState(0); useEffect(() => { const fragment = group.current!; const onClick = () => setClicks((c) => c + 1); fragment.addEventListener("click", onClick); return () => fragment.removeEventListener("click", onClick); }, []); return ( <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}> <Fragment ref={group}> <button>One</button> <button>Two</button> <button>Three</button> </Fragment> <button onClick={() => group.current?.focus()}>Focus the group</button> <span>Clicks inside the group: {clicks}</span> </div> );}
Match the pairs0/5 matched

Match each requirement to the tool that fits it best.

Choose an item, then its match on the other side.
Put it in order6 steps

Put the steps of a React view transition in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
View Transitions API
A browser API that snapshots the page before and after a DOM update and animates between the snapshots with CSS pseudo-elements.
ViewTransition
A React component that runs a view transition for its subtree when a transition, deferred value or Suspense reveal updates it.
enter, exit, update, share
The four kinds of animation a ViewTransition can get: inserted, removed, changed or moved, or paired by name with another boundary.
shared element transition
A morph between two elements with the same name, one leaving and one appearing in the same transition.
addTransitionType
Tags the current transition with a string, such as forward or back, so animation props can choose a class per type.
Motion
The animation library formerly called Framer Motion, imported from motion/react. Best for gestures, springs and drag.
Fragment ref
A ref on <Fragment> (React 19.3) that returns a FragmentInstance acting on the fragment's top-level DOM children.