AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

vercel-react-view-transitions

Guide for implementing smooth, native-feeling animations using React's View Transition API (`<ViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter/exit of components, animate list reorder, implement directional (forward/back) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries.

Original source
vercel-labs
License
MIT
Pinned revision
1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read vercel-labs--vercel-react-view-transitions at revision 1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 8

AGENTS.md · 24000

<ViewTransition name={...}> inside a deferred list triggers cross-fades on every keystroke. Fix with default="none":

{filteredItems.map(item => (
  <ViewTransition key={item.id} name={`item-${item.id}`} share="morph" default="none">
    <ItemCard item={item} />
  </ViewTransition>
))}

Card Expand/Collapse with startTransition

Toggle between grid and detail view with shared element morph:

'use client';

import { useState, useRef, startTransition, ViewTransition } from 'react';

export default function ItemGrid({ items }) {
  const [expandedId, setExpandedId] = useState(null);
  const scrollRef = useRef(0);

  return expandedId ? (
    <ViewTransition enter="slide-in" name={`item-${expandedId}`}>
      <ItemDetail
        item={items.find(i => i.id === expandedId)}
        onClose={() => {
          startTransition(() => {
            setExpandedId(null);
            setTimeout(() => window.scrollTo({ behavior: 'smooth', top: scrollRef.current }), 100);
          });
        }}
      />
    </ViewTransition>
  ) : (
    <div className="grid grid-cols-3 gap-4">
      {items.map(item => (
        <ViewTransition key={item.id} name={`item-${item.id}`}>
          <ItemCard
            item={item}
            onSelect={() => {
              scrollRef.current = window.scrollY;
              startTransition(() => setExpandedId(item.id));
            }}
          />
        </ViewTransition>
      ))}
    </div>
  );
}

Type-Safe Transition Helpers

Use as const arrays and derived types to prevent ID clashes:

const transitionTypes = ['default', 'transition-to-detail', 'transition-to-list'] as const;
const animationTypes = ['auto', 'none', 'animate-slide-from-left', 'animate-slide-from-right'] as const;

type TransitionType = (typeof transitionTypes)[number];
type AnimationType = (typeof animationTypes)[number];
type TransitionMap = { default: AnimationType } & Partial<Record<Exclude<TransitionType, 'default'>, AnimationType>>;

export function HorizontalTransition({ children, enter, exit }: {
  children: React.ReactNode;
  enter: TransitionMap;
  exit: TransitionMap;
}) {
  return <ViewTransition enter={enter} exit={exit}>{children}</ViewTransition>;
}

Cross-Fade Without Remount

Omit key to trigger an update (cross-fade) instead of exit + enter. Avoids Suspense remount/refetch:

<ViewTransition>
  <TabPanel tab={activeTab} />
</ViewTransition>

Use key when content identity changes (state resets). Omit for cross-fades (tabs, panels, carousel).

Isolate Elements from Parent Animations

Pull an element out of the animated root snapshot by giving it its own view-transition-name. view-transition-name: none is a no-op — it's the CSS default, so the element stays in root (a common flicker bug). Use a real, unique name, then neutralize with <ViewTransition default="none"> (no CSS) or CSS (needed for z-index/display control — see css-recipes.md).

  • Persistent chrome (nav, sidebar, player bar): <nav style={{ viewTransitionName: 'persistent-nav' }}> + isolation CSS. <ViewTransition default="none"> works too, but its auto-name can't take z-index/backdrop display:none — hand-name when you need those.
  • Floating elements (popovers, menus): left open, they're captured in root and flicker on settle. Real name + isolation (Floating Element Isolation). A static name is fine if only one is mounted (unmountOnHide); native top-layer (popover/<dialog>) settle-flicker is a browser limit.
  • Naming an interactive element has a cost: named participants are skipped by hit-testing while a transition runs (csswg#10930) — clicks and hover fall through to whatever is beneath. Portal named popovers/menus; rendered inline in a clickable row, mid-transition clicks activate the row and read as outside-clicks that close the popover.
  • Third-party floating components (toast libraries, portals you don't render): put the name on an always-mounted wrapper you own — <div style={{ viewTransitionName: 'toaster' }} className="pointer-events-none fixed inset-0">. Library containers often unmount when empty, so naming them directly leaves the group unpinned exactly when a toast appears mid-transition. Name a dialog's backdrop separately from its panel so each pins independently.

Suspense reveal flicker

An element rendered in both the fallback and the content flickers (opacity dip) on reveal — it fades against itself. Not a morph. Fix: render it outside the <Suspense> boundary (mount once, above it), or pin it with a view-transition-name.

<h1>{title}</h1>
<Suspense fallback={<BodySkeleton />}><Body /></Suspense>

Don't put a manual viewTransitionName on the root DOM node inside <ViewTransition> — React's auto-name overrides it.

Sliding Indicator (tabs)

One shared-name indicator rendered under the active tab morphs between positions on change (slide the group, disable old/new — see Sliding Indicator). Render it only under the active tab so exactly one element holds indicatorName; use a distinct indicatorName per tab strip. Trigger the state change inside startTransition so the move animates. Whatever owns active drives it — local state here, routing in Next (see Routing-Driven Tabs).

import { useState, useTransition, ViewTransition } from 'react';

export function Tabs({ tabs, indicatorName = 'tab-indicator' }) {
  const [active, setActive] = useState(tabs[0].value);
  const [, startTransition] = useTransition();
  return (
    <nav>
      {tabs.map(t => (
        <button key={t.value} type="button"
          aria-current={active === t.value ? 'page' : undefined}
          onClick={() => startTransition(() => setActive(t.value))}>
          <span>{t.label}</span>
          {active === t.value && (
            <ViewTransition name={indicatorName} share="tab-underline">
              <span className="active-underline" aria-hidden />
            </ViewTransition>
          )}
        </button>
      ))}
    </nav>
  );
}

Because the state change is a transition, if the newly-active tab renders suspending content the whole update — indicator and aria-current — waits for it to commit, and the strip feels dead on click. Give the controls an immediate value with useOptimistic (drive aria-current from it) so feedback is instant while the content streams. The routing variant (Routing-Driven Tabs) does exactly this: optimistic aria-current, committed active for the bar.

Layout Displacement Morph

Only content inside an activated boundary animates position — everything else teleports to its new layout spot. When a list grows or shrinks, wrap the sibling content below it so it glides instead of jumping:

<FavoritesList />              {/* rows enter/exit */}
<ViewTransition>               {/* bare: update enabled */}
  <section>
    <h2>You Might Also Like</h2>
    <Recommendations />
  </section>
</ViewTransition>

The section — heading included — morphs as one group when rows above are added or removed. Nothing inside the section changed; the displacement is the update.

  • React only measures boundaries that are direct children of nodes along the changed path — a VT buried under an extra wrapper element won't activate. Place the boundary as a direct sibling of the changing content.
  • Sometimes the better fix is no morph at all: pad fixed-size lists to a constant slot count with invisible fillers so the grid never changes height and nothing below it moves.
  • default="none" disables exactly this morph — it turns off update. Named/shared elements get default="none"; displaced siblings and keyed list items stay bare or set update="auto".

Reusable Animated Collapse

function AnimatedCollapse({ open, children }) {
  if (!open) return null;
  return (
    <ViewTransition enter="expand-in" exit="collapse-out">
      {children}
    </ViewTransition>
  );
}

// Usage: toggle with startTransition
<button onClick={() => startTransition(() => setOpen(o => !o))}>Toggle</button>
<AnimatedCollapse open={open}><SectionContent /></AnimatedCollapse>

Composing with Activity

Activity is orthogonal to view transitions: it preserves the state of a hidden subtree, ViewTransition animates it. Compose them for an in-page show/hide (drawer, panel, tab body) that keeps its scroll/form state while it animates in and out:

<Activity mode={isVisible ? 'visible' : 'hidden'}>
  <ViewTransition enter="slide-in" exit="slide-out">
    <Sidebar />
  </ViewTransition>
</Activity>

Only reach for Activity when there's state worth preserving — a stateless element (e.g. the sliding indicator above) gains nothing from it. In Next.js, layout-hosted chrome already persists across navigations without Activity (see nextjs.md).

Exclude Elements with useOptimistic

useOptimistic values update before the transition snapshot, excluding them from animation. Use for controls (labels); use committed state for animated content:

const [sort, setSort] = useState('newest');
const [optimisticSort, setOptimisticSort] = useOptimistic(sort);

function cycleSort() {
  const nextSort = getNextSort(optimisticSort);
  startTransition(() => {
    setOptimisticSort(nextSort);  // before snapshot — no animation
    setSort(nextSort);            // between snapshots — animates
  });
}

<button>Sort: {LABELS[optimisticSort]}</button>
{items.sort(comparators[sort]).map(item => (
  <ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition>
))}

View Transition Events

Imperative control via onEnter, onExit, onUpdate, onShare. Return a cleanup function to cancel your animation when the transition finishes. onShare takes precedence over onEnter/onExit.

<ViewTransition
  onEnter={(instance, types) => {
    const anim = instance.new.animate(
      [{ transform: 'scale(0.8)', opacity: 0 }, { transform: 'scale(1)', opacity: 1 }],
      { duration: 300, easing: 'ease-out' }
    );
    return () => anim.cancel();
  }}
>
  <Component />
</ViewTransition>

The instance object: instance.old, instance.new, instance.group, instance.imagePair, instance.name.

The types array (second argument) lets you vary animation based on transition type.


Animation Timing

| Interaction | Duration | |------------|----------| | Direct toggle (expand/collapse) | 100–200ms | | Route transition (slide) | 150–250ms | | Suspense reveal (skeleton → content) | 200–400ms | | Shared element morph | 300–500ms |


Troubleshooting

VT not activating: Ensure <ViewTransition> comes before any DOM node and the state update is inside startTransition. A raw viewTransitionName only isolates an element; it does not activate a React view transition.

"Two ViewTransition components with the same name": Names must be globally unique. Use IDs such as name={hero-${item.id}}. If a reusable component appears in multiple surfaces at once, move the name to the specific consumer or make it conditional.

Unrelated content crossfades: A bare VT uses the browser crossfade for every trigger. Set default="none" and opt in only to the triggers that boundary should handle.

Scrolling hangs while a transition animates: the ::view-transition overlay is position: fixed and its snapshots don't scroll — a browser limitation, not fixable in React (skipping snaps to the end). Keep reveal durations short; for scroll-driven UI use gesture transitions (experimental useSwipeTransition, if available).

Open popover flickers when a background transition settles: it's captured in root. Give it a real view-transition-name + isolation (not none) — see Isolate Elements from Parent Animations.

Popover closes or goes dead when clicked mid-transition: named participants are skipped by hit-testing while a transition runs; clicks land on what's beneath and read as outside-clicks. Portal the popover (see Isolate Elements from Parent Animations); brief dead clicks during the transition remain — that's the price of the name.

Shared morph silently not firing: share resolved to none. Either the VT has default="none" with no explicit share prop, or share is type-keyed and the navigation never adds the type — the link needs transitionTypes (or addTransitionType in the transition).

Shared morph competes with a page fade: A fading page exit dissolves the source while it is morphing. Remove that exit or use motion that preserves the shared element's continuity.

An enter animation runs even though Suspense never showed its fallback: The content-side VT became the topmost entering subtree during navigation. At that call site, add a host DOM element immediately outside Suspense. The host suppresses the nested enter during warm navigation but remains mounted so the VT can enter on a later fallback-to-content reveal. Keep the host outside Suspense, not inside the reusable crossfade; do nothing when a direct host already exists.

Section below a list teleports instead of gliding: it's outside any activated boundary, its VT has default="none" (which disables update), or it isn't an immediate sibling of the changing content. See Layout Displacement Morph.

router.back() and browser back/forward skip the directional slide: traversals carry no transition types, so type-keyed maps resolve to default — untyped shared-element morphs still apply. Use router.push() for typed animations.

flushSync skips animations: Use startTransition instead.

Only updates animate (no enter/exit): Without <Suspense>, React treats swaps as updates. Conditionally render the VT itself, or wrap in <Suspense>.

Suspense reveal does not animate: Suspense resolves in a separate transition without navigation types. Use string enter/exit props rather than a type map.

Layout VT prevents page VTs from animating: Nested VTs skip their own enter/exit when they mount or unmount as one unit with a parent VT. Keep route boundaries in pages, not a layout wrapping {children}. React has experimental upstream parentEnter/parentExit work (PR #36690), but those props are not currently available in the Next.js client runtime; do not recommend them in a Next.js app unless the installed runtime and docs explicitly include them.

Same-route content does not animate with update: Nested VTs can own the mutation before an outer boundary sees it. For a real identity change, use key with a stable name and share instead.

List reorder not animating with useOptimistic: Optimistic values resolve before snapshot. Use committed state for list order.

TS error "Property 'default' is missing": Type-keyed objects require a default key.

Hash fragments cause scroll jumps: Navigate without hash; scroll programmatically after navigation.

Backdrop-blur flickers: Use the Backdrop-Blur Workaround.

border-radius lost during transitions: Apply border-radius directly to the captured element.

Skeleton controls slide away: Give matching controls the same viewTransitionName.

Batching: Multiple updates during animation are batched. A→B→C→D becomes B→D.


CSS Animation Recipes

Ready-to-use CSS for <ViewTransition> props. Copy into your global stylesheet.

This file contains the complete CSS recipe set for the patterns in this skill. Copy only what the app needs.


Timing Variables

:root {
  --duration-exit: 150ms;
  --duration-enter: 210ms;
  --duration-move: 400ms;
}

Shared Keyframes

@keyframes fade {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slide {
  from { translate: var(--slide-offset); }
  to { translate: 0; }
}

@keyframes slide-y {
  from { transform: translateY(var(--slide-y-offset, 10px)); }
  to { transform: translateY(0); }
}

Fade

::view-transition-old(.fade-out) {
  animation: var(--duration-exit) ease-in fade reverse;
}
::view-transition-new(.fade-in) {
  animation: var(--duration-enter) ease-out var(--duration-exit) both fade;
}

Usage: <ViewTransition enter="fade-in" exit="fade-out" />

Keep the shared fade keyframe opacity-only. If a specific morph needs softness, give that class its own blur keyframe so ordinary content reveals stay crisp.


Slide (Vertical)

::view-transition-old(.slide-down) {
  animation:
    var(--duration-exit) ease-out both fade reverse,
    var(--duration-exit) ease-out both slide-y reverse;
}
::view-transition-new(.slide-up) {
  animation:
    var(--duration-enter) ease-in var(--duration-exit) both fade,
    var(--duration-move) ease-in both slide-y;
}

Usage:

<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
  <ViewTransition default="none" enter="slide-up"><Content /></ViewTransition>
</Suspense>

Directional Navigation

Separate Enter/Exit Classes

::view-transition-new(.slide-from-right) {
  --slide-offset: 60px;
  animation:
    var(--duration-enter) ease-out var(--duration-exit) both fade,
    var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.slide-to-left) {
  --slide-offset: -60px;
  animation:
    var(--duration-exit) ease-in both fade reverse,
    var(--duration-move) ease-in-out both slide reverse;
}

::view-transition-new(.slide-from-left) {
  --slide-offset: -60px;
  animation:
    var(--duration-enter) ease-out var(--duration-exit) both fade,
    var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.slide-to-right) {
  --slide-offset: 60px;
  animation:
    var(--duration-exit) ease-in both fade reverse,
    var(--duration-move) ease-in-out both slide reverse;
}

Single-Class Approach

::view-transition-old(.nav-forward) {
  --slide-offset: -60px;
  animation:
    var(--duration-exit) ease-in both fade reverse,
    var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.nav-forward) {
  --slide-offset: 60px;
  animation:
    var(--duration-enter) ease-out var(--duration-exit) both fade,
    var(--duration-move) ease-in-out both slide;
}

::view-transition-old(.nav-back) {
  --slide-offset: 60px;
  animation:
    var(--duration-exit) ease-in both fade reverse,
    var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.nav-back) {
  --slide-offset: -60px;
  animation:
    var(--duration-enter) ease-out var(--duration-exit) both fade,
    var(--duration-move) ease-in-out both slide;
}

Shared Element Morph

::view-transition-group(.morph) {
  animation-duration: var(--duration-move);
}

::view-transition-image-pair(.morph) {
  animation-name: via-blur;
}

@keyframes via-blur {
  30% { filter: blur(3px); }
}

Usage: <ViewTransition name={product-${id}} share="morph" />

Note: Shared element transitions take raster snapshots. For text with significant size differences (e.g., <h3> → <h1>), the old snapshot gets scaled up, producing a visible ghost artifact. Use text-morph for text shared elements.

Text Morph

Avoids raster scaling artifacts on text by hiding the old snapshot and showing the new text at full resolution:

::view-transition-group(.text-morph) {
  animation-duration: var(--duration-move);
}
::view-transition-old(.text-morph) {
  display: none;
}
::view-transition-new(.text-morph) {
  animation: none;
  object-fit: none;
  object-position: left top;
}

Usage: <ViewTransition name={title-${id}} share="text-morph" />


Scale

::view-transition-old(.scale-out) {
  animation: var(--duration-exit) ease-in scale-down;
}
::view-transition-new(.scale-in) {
  animation: var(--duration-enter) ease-out var(--duration-exit) both scale-up;
}

@keyframes scale-down {
  from { transform: scale(1); opacity: 1; }
  to { transform: scale(0.85); opacity: 0; }
}
@keyframes scale-up {
  from { transform: scale(0.85); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

Usage: <ViewTransition enter="scale-in" exit="scale-out" />


Interactivity During Transitions

The ::view-transition overlay captures all pointer events. React shrinks it to zero when the root group doesn't animate, but in-flight animations still block clicks. To pass clicks/hover through even while animating:

::view-transition {
  pointer-events: none;
}

Trade-offs: clicks can hit live elements under still-moving snapshots, and it only helps unnamed content — named participants are skipped by hit-testing for the transition's duration, no CSS override (csswg#10930). Weigh that before naming interactive elements; portal named popovers (see Isolate Elements from Parent Animations).


No Root Cross-Fade (Live Root)

The root cross-fades on every transition, freezing unnamed content behind a stale snapshot — hover and active styles stop rendering until it settles. ::view-transition-new(root) is a live capture, so disabling the root animation keeps unnamed regions rendering (and, with the pointer-events recipe above, interactive):

::view-transition-old(root) {
  display: none;
}
::view-transition-new(root) {
  animation: none;
}

Named and classed groups still animate — they stack above root. Trade-off: unnamed content swaps instantly, so regions that should fade need their own VT. This also removes the main reason to hand-name static chrome; keep names only for elements that must stack above animating groups.

Pairs well with enter-only reveals: skip the fallback-exit VT entirely (<ViewTransition enter="auto" default="none"> around the content, nothing on the skeleton) — the skeleton snaps out live while the content fades in.


Persistent Element Isolation

::view-transition-group(persistent-nav) {
  animation: none;
  z-index: 100;
}

Layer multiple pinned groups with z-index tiers — chrome at 100, toasts/overlays that must beat everything at 200.

Backdrop-Blur Workaround

For elements with backdrop-filter, hide the old snapshot to avoid flash:

::view-transition-old(persistent-nav) {
  display: none;
}
::view-transition-new(persistent-nav) {
  animation: none;
}

Floating Element Isolation (popovers, menus, tooltips, control clusters)

Same freeze as persistent chrome. A floating/interactive element left rendered while a background transition runs is otherwise captured in the root snapshot and flickers as it settles. Give it a real, unique view-transition-name (never none — that's the CSS default = no isolation) and:

::view-transition-group(popover) {
  animation: none;
  z-index: 100;
}
::view-transition-old(popover),
::view-transition-new(popover) {
  animation: none;
}

Sliding Indicator (tab underline / segmented pill)

One shared-name indicator morphs between positions. Slide the group; disable old/new so the solid bar slides instead of cross-fading:

::view-transition-group(.tab-underline) {
  animation-duration: 220ms;
  animation-timing-function: cubic-bezier(0.5, 0, 0.2, 1);
}
::view-transition-old(.tab-underline),
::view-transition-new(.tab-underline) {
  animation: none;
  height: 100%;
}

Reduced Motion

@media (pr