# View transitions

> Navigations are an instant swap; a shared element is the transition worth having, and the page fade is the one to think twice about.

A navigation is an instant swap: the layouts stay mounted and the page under
them changes. Nothing fades, and nothing needs to. **Most apps need nothing on
this page.**

The transition worth adding is a *shared element*: a product image that morphs
from the list into the detail page. Give it the same `name` on both pages:

```tsx title="src/app/products/ProductImage.tsx"
import { ViewTransition } from 'react';

export function ProductImage({ product }: { product: { id: string; image: string } }) {
  return (
    <ViewTransition name={`product-${product.id}`}>
      <img src={product.image} alt="" />
    </ViewTransition>
  );
}
```

`<ViewTransition>` is React's, from 19.3, and hands the change to the browser's
View Transition API. See [Requirements](#requirements).

## Morphing an element between pages

Render the same `name` on the list page and the detail page, and the browser
morphs the element from where it was to where it is:

```tsx title="src/app/products/page.tsx"
import Link from '@rsc-kit/core/Link';
import { ProductImage } from './ProductImage';

export default async function ProductsPage() {
  const products = await listProducts();

  return products.map((product) => (
    <Link key={product.id} href={`/products/${product.id}`}>
      <ProductImage product={product} />
      {product.name}
    </Link>
  ));
}
```

```tsx title="src/app/products/[id]/page.tsx"
import { ProductImage } from '../ProductImage';

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const product = await findProduct((await params).id);

  return (
    <article>
      <ProductImage product={product} />
      <h1>{product.name}</h1>
    </article>
  );
}
```

A navigation replaces the page inside `startTransition`, so this works with no
other code. One element is one snapshot the size of that element, which is
cheap in every browser.

## Animating a change on the page

Give the changing element a `key`, so React sees a replacement rather than an
edit, and commit the change inside `startTransition`:

```tsx title="src/components/Total.tsx"
'use client';

import { useState, startTransition, ViewTransition } from 'react';
import { addToTotal } from '../actions';

export function Total() {
  const [total, setTotal] = useState<number | null>(null);

  return (
    <>
      <ViewTransition>
        <p key={String(total)}>{total ?? '—'}</p>
      </ViewTransition>

      <button
        onClick={() =>
          startTransition(async () => {
            const next = await addToTotal(1);

            startTransition(() => setTotal(next));
          })
        }
      >
        add
      </button>
    </>
  );
}
```

A server action's result is an ordinary return value, so putting it into state
is a transition like any other.

### What animates

A transition that doesn't run looks exactly like one you styled badly, so check
the change comes from one of these:

| the change comes from | animates |
| --- | --- |
| your own `useState`, inside `startTransition` | yes |
| a server action's result, put into state | yes |
| `<Form>`: errors, success, optimistic updates | yes, it is built on `useState` |
| a streamed `<Suspense>` boundary arriving | yes, React does this on its own |
| navigating to another page | yes, the update carries a transition type |

## Fading the whole page

A fade over the whole page is cosmetic and never makes a navigation faster. If
you want it, use `PageTransition` in the root layout:

```tsx title="src/app/layout.tsx"
import { PageTransition } from '@rsc-kit/core/PageTransition';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body className="min-h-full flex flex-col">
        <PageTransition className="flex flex-1 flex-col">{children}</PageTransition>
      </body>
    </html>
  );
}
```

It is a 120 ms cross-fade on navigations only, never on a first load or a
reload. It is skipped on WebKit and for a visitor who asked for reduced
motion. Its CSS ships with it, so there is nothing to add to your stylesheet.

`className` goes on the one `<div>` it wraps the page in, so here the `<div>`
carries the body's flex layout. To leave the navbar out of the fade, put
`PageTransition` around `<main>` in a nested layout instead.

### Changing the fade

```tsx
<PageTransition duration={200}>{children}</PageTransition>   // ms; 0 is the instant swap
<PageTransition webkit="run">{children}</PageTransition>     // a short page that may run it on WebKit
<PageTransition transition="slide">{children}</PageTransition> // the class your own CSS styles
```

| Prop | Default | What it does |
| --- | --- | --- |
| `duration` | `120` | The fade's length in ms. `0` is the instant swap, and named shared elements still morph. |
| `webkit` | `"skip"` | `"run"` for a page you have measured, such as a form, where the snapshot is one screen. |
| `transition` | `"page"` | The view-transition class a navigation gets. |
| `className` | | The class of the wrapping `<div>`. |

To shape the fade further, style the class yourself. Your rules come after the
component's:

```css title="src/app/styles.css"
::view-transition-old(.page),
::view-transition-new(.page) {
  animation-timing-function: ease-out;
}
```

### Why WebKit is skipped

Safari, and every browser on iOS since they all run WebKit, rasterises the
outgoing snapshot at the element's full height, not the viewport's. A landing
page 12,000 px tall is 44 megapixels at 3×. A port measured about 600 ms with
the screen frozen on every navigation away from it, and the memory can be
enough for iOS to discard the tab. Chromium caps the snapshot, so a desktop or
an Android phone never shows it.

So `PageTransition` runs the fade on Chromium and Firefox, and skips it where
`navigator.vendor` is Apple's. That is decided after mount, so the first render
agrees with the server's.

Writing the boundary yourself, do the same, or put it on a container that is
the viewport's height and scrolls inside, so the snapshot is one screen.

## Pages that ship no JavaScript

A page with nothing interactive ships no runtime, so a link from it is an
ordinary page load and there is no router to run `<ViewTransition>`. The browser
can still animate that load with one rule of CSS:

```css title="src/app/styles.css"
@media (prefers-reduced-motion: no-preference) {
  @view-transition {
    navigation: auto;
  }
}
```

With it on both pages, a same-site link cross-fades from one document to the
next. Shape it with the same `::view-transition-*` selectors, and give an
element `view-transition-name` on both pages for a shared one. Chrome, Edge
and Safari 18.2+ do it; elsewhere the link is the page load it always was.

The WebKit cost above applies here too. On pages that ship the runtime the rule
has no effect, since their navigations are the router's.

## Coming back to a page you were just on

A link to a page still being held reveals it rather than refetching it, so a
half-filled form is still filled in. That lasts thirty seconds by default,
which covers leaving a form to check something and coming straight back.
After that a link refetches, because the held page's data is from when you
left. To always refetch:

```ts
import { setRevealWindow } from '@rsc-kit/core/navigate';

setRevealWindow(0); // every link is a fresh request
```

The back button isn't bounded. It names a moment, and the page from that
moment is the right answer however old it is.

<Aside type="caution" title="It can hide a server that is down">
  Revealing a held page fetches nothing, so those navigations keep working
  when the backend does not. Measured with the process killed: a page visited
  moments ago still navigates, one never visited does not. That is a reveal
  window rather than offline support, and it means a dead server can go
  unnoticed for as long as the window lasts — [`useOffline`](/guides/offline)
  is what surfaces it. Actually surviving with no network is
  [`offline: true`](/guides/offline#working-with-no-network-at-all), which is a service
  worker and a different thing entirely.
</Aside>

## Requirements

`react` and `react-dom` at **19.3 or newer**. A scaffolded app pins `^19.2`, so
this is an upgrade:

```bash
npm install react@^19.3 react-dom@^19.3
```

React also documents a [`browser`](https://react.dev/reference/react-dom/browser)
api for rendering a component only in the browser. It is not in 19.3 yet; see
[static generation](/guides/static-generation#a-value-that-must-not-be-frozen)
for what to do meanwhile.

## How the page fade works

- **Only navigations.** A navigation's update carries the transition type
  `rsc-navigation`, and the first commit after hydration doesn't. `PageTransition`
  is `<ViewTransition default={{ 'rsc-navigation': 'page', default: 'none' }}>`
  around one `<div>`, so a first load or a reload never animates.
- **One wrapper element.** React names each top-level element under a boundary
  and animates every one on its own, so a page of five sections would be five
  groups morphing separately. One wrapper is one snapshot pair: the old page
  and the new one dissolving into each other. Write the `ViewTransition`
  yourself, without the wrapper, when you want the per-element movement.
- **The durations.** The browser's default is 250 ms, and the group and root
  pairs keep it whatever you set on the page pair. A "120 ms" fade written as
  the two-selector rule most examples show ran 290 ms, so the component sets
  all of them.
- **A second tap.** The pseudo-element tree sits over the document while the
  fade runs. The component adds `::view-transition { pointer-events: none }`, so
  it doesn't swallow a tap.
