Activity and View Transitions

Hide UI without losing state, and animate between states.

Builds on Suspense and use.

The last three chapters were about when React shows new UI: transitions keep old content while new content renders, Actions track async work, Suspense waits for data and code. This chapter covers two newer components that change how UI comes and goes. <Activity> React 19.2 hides part of the tree without destroying it, so a tab you leave keeps its state and can even render before you open it. <ViewTransition> React 19.3 animates between the old and new UI of a transition using the browser's View Transition API.

Both are stable in React 19.3.1 and exported from react. Both build directly on the scheduling ideas from rendering and scheduling: hidden Activity content renders in the lowest-priority lane, and only transitions animate.

The problem: tabs that forget, or tabs that never stop#

The reading list app has two tabs: Notes, where you're drafting a note, and Timer, which counts how long you've been reading with a setInterval in an effect. Pick a hiding strategy, type a draft, let the timer run, switch tabs a few times and watch the console.

Three ways to hide a tab
import { Activity, useEffect, useState, type ReactNode } from "react";

type Strategy = "conditional" | "css" | "activity";

function Notes() {
  const [draft, setDraft] = useState("");
  return <textarea rows={3} placeholder="Notes on chapter 3..." value={draft} onChange={(e) => setDraft(e.target.value)} />;
}

function Timer() {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    console.log("Timer effect: start interval");
    const id = setInterval(() => {
      console.log("tick");
      setSeconds((s) => s + 1);
    }, 1000);
    return () => {
      clearInterval(id);
      console.log("Timer effect: cleanup");
    };
  }, []);
  return <p>Reading for {seconds}s</p>;
}

function Panel({ strategy, visible, children }: { strategy: Strategy; visible: boolean; children: ReactNode }) {
  if (strategy === "conditional") return visible ? <>{children}</> : null;
  if (strategy === "css") return <div style={{ display: visible ? undefined : "none" }}>{children}</div>;
  return <Activity mode={visible ? "visible" : "hidden"}>{children}</Activity>;
}

export default function App() {
  const [strategy, setStrategy] = useState<Strategy>("conditional");
  const [tab, setTab] = useState<"notes" | "timer">("notes");
  return (
    <>
      <p>
        {(["conditional", "css", "activity"] as const).map((s) => (
          <label key={s} style={{ marginRight: 12 }}>
            <input type="radio" checked={strategy === s} onChange={() => setStrategy(s)} /> {s}
          </label>
        ))}
      </p>
      <p>
        <button onClick={() => setTab("notes")} disabled={tab === "notes"}>Notes</button>{" "}
        <button onClick={() => setTab("timer")} disabled={tab === "timer"}>Timer</button>
      </p>
      <div key={strategy}>
        <Panel strategy={strategy} visible={tab === "notes"}>
          <Notes />
        </Panel>
        <Panel strategy={strategy} visible={tab === "timer"}>
          <Timer />
        </Panel>
      </div>
    </>
  );
}
Nothing logged yet.

With conditional rendering, leaving a tab unmounts it. The draft is gone and the timer restarts from zero. With css (display: none), everything survives, but the hidden timer keeps ticking and re-rendering in the background, and its interval keeps running even though nobody can see it. Multiply that by a dashboard of hidden panels, each with subscriptions and polling, and "keep everything mounted" gets expensive. With activity, the draft survives, the timer's count is preserved, and the console shows the effect cleaning up when you leave and starting again when you come back.

<Activity> React 19.2#

import { Activity } from "react";

<Activity mode={isVisible ? "visible" : "hidden"}>
  <Sidebar />
</Activity>;

mode is "visible" (the default) or "hidden". When an Activity becomes hidden, React:

  • keeps the state of every component inside, and keeps their DOM, hidden with display: none;
  • cleans up their effects, running the cleanup functions as if the components unmounted, and re-creates them when the Activity becomes visible again;
  • keeps rendering them when their props change, at the lowest priority, after everything visible is done. In lane terms, hidden content goes in the offscreen lane at the bottom of the ladder.

The docs give the right mental model: think of a hidden Activity as unmounted, with its state saved. Your effects should already handle unmounting correctly, so they handle hiding correctly too. That's why Strict Mode's double-invoke of effects in development is good preparation: a component that survives mount, cleanup, mount is ready for Activity.

Three ways to hide a tab
{show && <Tab />}display: none<Activity mode="hidden">React statelostkeptkeptDOM (inputs, scroll)removedkeptkept, hiddenEffects while hiddencleaned upkeep runningcleaned upUpdates while hiddennonefull prioritylow priorityShowing it againfull mountjust CSSeffects re-run
Conditional rendering throws everything away. CSS hiding keeps everything, including subscriptions and timers that keep running and renders that compete with visible UI. A hidden Activity keeps state and DOM but behaves as if unmounted: effects are cleaned up and its updates wait until nothing else needs the main thread.

Pre-rendering what the user will open next#

A hidden Activity also renders on the initial render, at low priority and without mounting effects. Combined with Suspense, that means a hidden tab can load its code and data before anyone opens it.

Pre-render a tab before it's opened

Both tabs load a book that takes 1.5 seconds. Wait two seconds, then open each.

import { Activity, Suspense, use, useState } from "react";
import { fakeFetch } from "guide-tools";

const cache = new Map<string, Promise<any>>();
function load(path: string) {
  if (!cache.has(path)) cache.set(path, fakeFetch(path, { delay: 1500 }));
  return cache.get(path)!;
}

function BookCard({ id }: { id: number }) {
  const book = use(load(`/books/${id}`));
  return (
    <p>
      <strong>{book.title}</strong> by {book.author} ({book.year})
    </p>
  );
}

export default function App() {
  const [tab, setTab] = useState<"home" | "prerendered" | "onDemand">("home");
  return (
    <>
      <button onClick={() => setTab("home")}>Home</button>{" "}
      <button onClick={() => setTab("prerendered")}>Book 2 (pre-rendered)</button>{" "}
      <button onClick={() => setTab("onDemand")}>Book 3 (on demand)</button>
      {tab === "home" ? <p>Pick a book.</p> : null}

      <Activity mode={tab === "prerendered" ? "visible" : "hidden"}>
        <Suspense fallback={<p>Loading book 2...</p>}>
          <BookCard id={2} />
        </Suspense>
      </Activity>

      {tab === "onDemand" ? (
        <Suspense fallback={<p>Loading book 3...</p>}>
          <BookCard id={3} />
        </Suspense>
      ) : null}
    </>
  );
}

Book 2 appears instantly because its hidden Activity rendered on load, suspended on the request and kept the result. Book 3 only starts loading when you click. Pre-rendering only picks up work that suspends (use on a promise, lazy). Data fetched in an effect isn't loaded, because effects don't run while hidden.

Caveats worth knowing#

  • The DOM isn't destroyed, so DOM side effects can continue. A hidden <video> keeps playing and an <iframe> keeps running. The docs recommend pausing in an effect cleanup (they use useLayoutEffect, since its cleanup is tied to the UI being hidden):

    useLayoutEffect(() => {
      const video = videoRef.current!;
      return () => video.pause();
    }, []);
  • Bare text is emptied, not hidden. A text node can't take display: none, so React hides text rendered directly inside an Activity by setting it to an empty string and restores it when shown. That's invisible to users, but code that reads the DOM of hidden content sees the difference.

  • Effects that "run once on mount" now run on every show. If an effect logs an analytics page view or starts a fetch on mount, it fires again each time the Activity becomes visible. That's usually correct (the user is viewing it again), but check.

  • Memory. Hidden content stays in memory with its state and DOM. Hiding ten heavy tabs keeps ten heavy trees around. Use Activity for things the user is likely to come back to.

<ViewTransition> React 19.3#

The second problem is purely visual. When a transition swaps one UI for another, the change is instant, and instant changes are disorienting: items jump to new positions in a sorted list, a new page replaces the old with no sense of direction. Browsers now have a built-in answer, the View Transition API: document.startViewTransition(update) snapshots the page, runs your update, snapshots again, and animates between the two with CSS you control. Driving it by hand from React is awkward, because you need the snapshot taken right before React touches the DOM and the update callback to contain exactly React's commit.

<ViewTransition> makes React do that coordination.

import { ViewTransition } from "react";

<ViewTransition>
  <BookDetails book={book} />
</ViewTransition>;
What happens during a <ViewTransition>
rendertransition lanesnapshot oldstartViewTransitioncommitsnapshot newanimate::view-transition-*clean upnames removedReactReact and the browserThe browser (CSS)startTransition(() => setIndex(i + 1))div.style.viewTransitionName = "<generated name>"
Step 1 of 5

An update starts inside startTransition (or comes from useDeferredValue or a Suspense reveal). React renders the new tree as usual. Nothing on screen has changed yet. A plain setState would skip everything that follows and just commit.

What animates, and when#

  • Only transitions animate. Updates inside startTransition, from useDeferredValue, or from a Suspense boundary revealing content activate <ViewTransition>. A plain setState commits immediately with no animation, on the principle that urgent updates should feel instant. If flushSync runs mid-transition, React skips the animation.
  • Four kinds of animation, decided by how the boundary changed:
    • enter: the <ViewTransition> was inserted in this transition;
    • exit: it was removed;
    • update: React changed DOM inside it, or it moved or resized because of a sibling;
    • share: a <ViewTransition> with a given name was removed in one place and one with the same name was inserted elsewhere in the same transition, so the element appears to move between them.
  • For enter and exit to fire, the <ViewTransition> must come before any DOM node in the subtree being inserted or removed. <div><ViewTransition>... inside a newly inserted subtree won't trigger enter.
  • The default animation is the browser's cross-fade. Each kind can be set with a prop: enter, exit, update, share, or default for all of them. A value is "auto" (browser default), "none" (no animation) or a View Transition Class, a class name you style with ::view-transition-old(.my-class) and ::view-transition-new(.my-class).

Here's the reading list sorted two ways. Each item is wrapped in its own keyed <ViewTransition>, so when the order changes, each item animates from its old position to its new one.

Animate a re-sort

Sort with and without Animate. Without it, the sort is a plain setState, which never animates.

import { startTransition, useState, ViewTransition } from "react";
import { books } from "guide-tools";

type Order = "title" | "year";

export default function App() {
  const [order, setOrder] = useState<Order>("title");
  const [animate, setAnimate] = useState(true);

  const sorted = [...books].sort((a, b) => (order === "year" ? a.year - b.year : a.title.localeCompare(b.title)));

  function sortBy(next: Order) {
    if (animate) startTransition(() => setOrder(next));
    else setOrder(next);
  }

  return (
    <>
      <label>
        <input type="checkbox" checked={animate} onChange={(e) => setAnimate(e.target.checked)} /> Animate (startTransition)
      </label>
      <p>
        <button onClick={() => sortBy("title")} disabled={order === "title"}>Sort by title</button>{" "}
        <button onClick={() => sortBy("year")} disabled={order === "year"}>Sort by year</button>
      </p>
      <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
        {sorted.map((b) => (
          <ViewTransition key={b.id}>
            <li style={{ padding: "4px 8px", margin: "3px 0", border: "1px solid #d6d3d1", borderRadius: 6, background: "white" }}>
              {b.year} · {b.title}
            </li>
          </ViewTransition>
        ))}
      </ul>
    </>
  );
}

Wrapping the whole <ul> in one <ViewTransition> instead would cross-fade the list as a single image. Per-item boundaries are what let items move individually.

addTransitionType: animate by cause#

The same state change can deserve different animations depending on why it happened. Going to the next book should slide left; going back should slide right. addTransitionType(type), called inside startTransition, labels the transition, and a <ViewTransition> prop can be an object keyed by type:

Next and previous with transition types
import { addTransitionType, startTransition, useState, ViewTransition } from "react";
import { books } from "guide-tools";
import "./styles.css";

export default function App() {
  const [index, setIndex] = useState(0);
  const book = books[index];

  function go(step: 1 | -1) {
    startTransition(() => {
      addTransitionType(step === 1 ? "next" : "previous");
      setIndex((i) => (i + step + books.length) % books.length);
    });
  }

  return (
    <>
      <button onClick={() => go(-1)}>Previous</button> <button onClick={() => go(1)}>Next</button>
      <div className="stage">
        <ViewTransition
          key={book.id}
          enter={{ next: "slide-from-right", previous: "slide-from-left", default: "auto" }}
          exit={{ next: "slide-to-left", previous: "slide-to-right", default: "auto" }}
        >
          <div className="card">
            <strong>{book.title}</strong>
            <div>
              {book.author}, {book.year}
            </div>
          </div>
        </ViewTransition>
      </div>
    </>
  );
}

Changing the key makes the old card exit and the new card enter in the same transition, and the type picks which pair of classes applies. React also passes the types to the browser's view transition, so CSS can match them with :active-view-transition-type(next). For imperative control there are event props (onEnter, onExit, onUpdate, onShare), each called with the pseudo-element instances and the types, which can drive the Web Animations API and should return a cleanup.

Notice the prefers-reduced-motion block. React doesn't turn animations off for users who ask for reduced motion. That's your CSS's job.

Shared elements#

Give two boundaries the same name, render one in the old UI and the other in the new, and the browser morphs one into the other: a book cover in a list growing into the cover on its detail page.

// In the list
<ViewTransition name={`cover-${book.id}`}>
  <img src={book.cover} alt="" />
</ViewTransition>

// On the detail page, rendered in the same transition
<ViewTransition name={`cover-${book.id}`}>
  <img src={book.cover} alt="" className="large" />
</ViewTransition>

A name must be mounted only once in the whole app at any time, so include an ID. Pairing is skipped when either side is outside the viewport.

Browser support and fallback#

<ViewTransition> is built on document.startViewTransition, which MDN lists as Baseline 2025 ("newly available" since October 2025) across current Chrome, Edge, Firefox and Safari. Older browsers lack it, and so do some embedded webviews. React handles that gracefully: if starting the view transition fails, it commits the update without animating, so the UI is always correct and the animation is a progressive enhancement. <ViewTransition> currently works only in React DOM; React Native support is planned.

A few more details from the reference: if a view transition is already running, the next one waits, and updates that arrive meanwhile are batched into a single next animation. Don't call document.startViewTransition yourself in a React app; React would interrupt it. And Back navigation via the legacy popstate event isn't animated.

Pitfalls#

Check your understanding#

Fix itThe draft disappears

Switching from Notes to Stats and back throws away the draft. Keep the draft without moving its state out of Notes, while still showing only one tab at a time. The checks type a draft, switch tabs and come back.

import { useState } from "react";
import { books } from "guide-tools";

function Notes() {
  const [draft, setDraft] = useState("");
  return (
    <>
      <label htmlFor="draft">Draft</label> <textarea id="draft" value={draft} onChange={(e) => setDraft(e.target.value)} />
    </>
  );
}

function Stats() {
  return <p>{books.length} books on the shelf</p>;
}

export default function App() {
  const [tab, setTab] = useState<"notes" | "stats">("notes");
  return (
    <>
      <button onClick={() => setTab("notes")}>Notes tab</button>{" "}
      <button onClick={() => setTab("stats")}>Stats tab</button>
      {tab === "notes" ? <Notes /> : null}
      {tab === "stats" ? <Stats /> : null}
    </>
  );
}
PredictWhat does the console say?

The Activity starts visible. The user hides it, then shows it again. What's logged, in order, after the initial mount?

function Feed() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("subscribe", count);
    return () => console.log("unsubscribe", count);
  }, [count]);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

<Activity mode={visible ? "visible" : "hidden"}>
  <Feed />
</Activity>;

The user clicks the button twice before hiding it.

Quick checkWill it animate?

A list item is wrapped in <ViewTransition>. Which update animates its removal?

Quick checkHidden, but still playing

A playing <video> sits inside an <Activity> that becomes hidden. What happens to the sound?

Explain it out loudHiding UI

An interviewer asks: "You have a tabbed dashboard. How do you hide inactive tabs, and what are the trade-offs of conditional rendering, CSS hiding and <Activity>?"

Interview angle

Say it in 30 seconds

Activity, stable since React 19.2, hides part of the tree without destroying it. A hidden Activity keeps state and DOM, hides it with display none, cleans up its effects as if it unmounted, and renders it only at the lowest priority, so it can also pre-render a tab's data and code before it's opened. ViewTransition, stable in 19.3, animates transitions with the browser's View Transition API: React snapshots, commits and lets CSS animate enter, exit, update and shared-element changes. Only transitions animate, addTransitionType picks animations by cause, and browsers without the API just skip the animation.

What does <Activity> do, and how is it different from conditional rendering?

basic

How can Activity make a screen appear instantly?

intermediate

How does <ViewTransition> work?

intermediate

Why doesn't my ViewTransition animate when I call setState?

intermediate

What is addTransitionType for?

senior

Would you ship Activity and ViewTransition to production today?

senior

Recap#

  • <Activity mode="hidden"> (19.2) keeps a subtree's state and DOM, hides it with display: none, cleans up its effects and renders it only at the lowest priority. Think of it as unmounted with its state saved.
  • A hidden Activity pre-renders on load, so a tab's code and data (anything that suspends) can be ready before it's opened. Effect-based fetching isn't picked up.
  • <ViewTransition> (19.3) animates transitions with the browser's View Transition API: enter, exit, update and share, each styled with View Transition Classes. Plain urgent updates never animate.
  • addTransitionType labels a transition so the same update can animate differently by cause. Shared elements need app-wide unique names.
  • Browsers without document.startViewTransition simply get the update without animation. Respect prefers-reduced-motion in your CSS; React won't do it for you.

Sources#