diff --git a/.github/workflows/analyze_comment.yml b/.github/workflows/analyze_comment.yml
index 1e086b9b7..fcac37738 100644
--- a/.github/workflows/analyze_comment.yml
+++ b/.github/workflows/analyze_comment.yml
@@ -6,8 +6,11 @@ on:
types:
- completed
-permissions: {}
-
+permissions:
+ contents: read
+ issues: write
+ pull-requests: write
+
jobs:
comment:
runs-on: ubuntu-latest
diff --git a/next-env.d.ts b/next-env.d.ts
index 3cd7048ed..52e831b43 100644
--- a/next-env.d.ts
+++ b/next-env.d.ts
@@ -1,6 +1,5 @@
///
///
-///
// NOTE: This file should not be edited
-// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
diff --git a/public/fonts/Source-Code-Pro-Bold.woff2 b/public/fonts/Source-Code-Pro-Bold.woff2
new file mode 100644
index 000000000..220bd5d96
Binary files /dev/null and b/public/fonts/Source-Code-Pro-Bold.woff2 differ
diff --git a/public/fonts/Source-Code-Pro-Regular.woff2 b/public/fonts/Source-Code-Pro-Regular.woff2
index 655cd9e81..fd665c465 100644
Binary files a/public/fonts/Source-Code-Pro-Regular.woff2 and b/public/fonts/Source-Code-Pro-Regular.woff2 differ
diff --git a/public/images/blog/react-labs-april-2025/perf_tracks.png b/public/images/blog/react-labs-april-2025/perf_tracks.png
new file mode 100644
index 000000000..835a247cf
Binary files /dev/null and b/public/images/blog/react-labs-april-2025/perf_tracks.png differ
diff --git a/public/images/blog/react-labs-april-2025/perf_tracks.webp b/public/images/blog/react-labs-april-2025/perf_tracks.webp
new file mode 100644
index 000000000..88a7eb792
Binary files /dev/null and b/public/images/blog/react-labs-april-2025/perf_tracks.webp differ
diff --git a/public/images/blog/react-labs-april-2025/perf_tracks_dark.png b/public/images/blog/react-labs-april-2025/perf_tracks_dark.png
new file mode 100644
index 000000000..07513fe90
Binary files /dev/null and b/public/images/blog/react-labs-april-2025/perf_tracks_dark.png differ
diff --git a/public/images/blog/react-labs-april-2025/perf_tracks_dark.webp b/public/images/blog/react-labs-april-2025/perf_tracks_dark.webp
new file mode 100644
index 000000000..1a0521bf8
Binary files /dev/null and b/public/images/blog/react-labs-april-2025/perf_tracks_dark.webp differ
diff --git a/src/components/Icon/IconExperimental.tsx b/src/components/Icon/IconExperimental.tsx
new file mode 100644
index 000000000..0bba612eb
--- /dev/null
+++ b/src/components/Icon/IconExperimental.tsx
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ */
+
+import {memo} from 'react';
+
+export const IconExperimental = memo<
+ JSX.IntrinsicElements['svg'] & {title?: string; size?: 's' | 'md'}
+>(function IconCanary(
+ {className, title, size} = {
+ className: undefined,
+ title: undefined,
+ size: 'md',
+ }
+) {
+ return (
+
+ {title && {title} }
+
+
+
+
+
+
+ );
+});
diff --git a/src/components/Layout/HomeContent.js b/src/components/Layout/HomeContent.js
index cfd3f6e6b..7e82e70e0 100644
--- a/src/components/Layout/HomeContent.js
+++ b/src/components/Layout/HomeContent.js
@@ -860,7 +860,8 @@ function ExampleLayout({
+ className="relative mt-0 lg:-my-20 w-full p-2.5 xs:p-5 lg:p-10 flex grow justify-center"
+ dir="ltr">
{right}
}
right={
-
+
-
+
}
/>
);
diff --git a/src/components/Layout/Page.tsx b/src/components/Layout/Page.tsx
index 1040e1aa7..c3224e517 100644
--- a/src/components/Layout/Page.tsx
+++ b/src/components/Layout/Page.tsx
@@ -31,7 +31,7 @@ interface PageProps {
meta: {
title?: string;
titleForTitleTag?: string;
- canary?: boolean;
+ version?: 'experimental' | 'canary';
description?: string;
};
section: 'learn' | 'reference' | 'community' | 'blog' | 'home' | 'unknown';
@@ -53,7 +53,7 @@ export function Page({
routeTree
);
const title = meta.title || route?.title || '';
- const canary = meta.canary || false;
+ const version = meta.version;
const description = meta.description || route?.description || '';
const isHomePage = cleanedPath === '/';
const isBlogIndex = cleanedPath === '/blog';
@@ -70,7 +70,7 @@ export function Page({
)}>
-
-
- {children}
-
-
+
+ {children}
+
{!isBlogIndex && (
+ )}
+ {version === 'experimental' && (
+
)}
diff --git a/src/components/Layout/TopNav/TopNav.tsx b/src/components/Layout/TopNav/TopNav.tsx
index cc5c654e3..a4b431189 100644
--- a/src/components/Layout/TopNav/TopNav.tsx
+++ b/src/components/Layout/TopNav/TopNav.tsx
@@ -266,7 +266,9 @@ export default function TopNav({
-
+
(
{children}
);
+const Experimental = ({children}: {children: React.ReactNode}) => (
+ {children}
+);
+
const NextMajor = ({children}: {children: React.ReactNode}) => (
{children}
);
@@ -121,6 +125,20 @@ const CanaryBadge = ({title}: {title: string}) => (
);
+const ExperimentalBadge = ({title}: {title: string}) => (
+
+
+ Experimental only
+
+);
+
const NextMajorBadge = ({title}: {title: string}) => (
));
return (
-
+
{sequential ? (
@@ -354,7 +372,7 @@ function IllustrationBlock({
)}
-
+
);
}
@@ -511,6 +529,8 @@ export const MDXComponents = {
MathI,
Note,
Canary,
+ Experimental,
+ ExperimentalBadge,
CanaryBadge,
NextMajor,
NextMajorBadge,
diff --git a/src/components/MDX/Sandpack/template.ts b/src/components/MDX/Sandpack/template.ts
index 7fbd537e7..dd6fd12bd 100644
--- a/src/components/MDX/Sandpack/template.ts
+++ b/src/components/MDX/Sandpack/template.ts
@@ -1,7 +1,7 @@
export const template = {
'/src/index.js': {
hidden: true,
- code: `import React, { StrictMode } from "react";
+ code: `import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";
diff --git a/src/components/PageHeading.tsx b/src/components/PageHeading.tsx
index 6000c8e51..3f15afe95 100644
--- a/src/components/PageHeading.tsx
+++ b/src/components/PageHeading.tsx
@@ -8,10 +8,12 @@ import {H1} from './MDX/Heading';
import type {RouteTag, RouteItem} from './Layout/getRouteMeta';
import * as React from 'react';
import {IconCanary} from './Icon/IconCanary';
+import {IconExperimental} from './Icon/IconExperimental';
interface PageHeadingProps {
title: string;
- canary?: boolean;
+ version?: 'experimental' | 'canary';
+ experimental?: boolean;
status?: string;
description?: string;
tags?: RouteTag[];
@@ -21,7 +23,7 @@ interface PageHeadingProps {
function PageHeading({
title,
status,
- canary,
+ version,
tags = [],
breadcrumbs,
}: PageHeadingProps) {
@@ -31,9 +33,15 @@ function PageHeading({
{breadcrumbs ? : null}
{title}
- {canary && (
+ {version === 'canary' && (
+ )}
+ {version === 'experimental' && (
+
)}
diff --git a/src/components/Seo.tsx b/src/components/Seo.tsx
index 628085744..b8a8394b6 100644
--- a/src/components/Seo.tsx
+++ b/src/components/Seo.tsx
@@ -124,7 +124,14 @@ export const Seo = withRouter(
)}
+
+
+### React Compiler is now in RC! {/*react-compiler-is-now-in-rc*/}
+
+Please see the [RC blog post](/blog/2025/04/21/react-compiler-rc) for details.
+
+
+
The React team is excited to share new updates:
diff --git a/src/content/blog/2024/12/05/react-19.md b/src/content/blog/2024/12/05/react-19.md
index aac80a44f..65bf42757 100644
--- a/src/content/blog/2024/12/05/react-19.md
+++ b/src/content/blog/2024/12/05/react-19.md
@@ -410,7 +410,7 @@ New function components will no longer need `forwardRef`, and we will be publish
-`refs` passed to classes are not passed as props since they reference the component instance.
+`ref`s passed to classes are not passed as props since they reference the component instance.
diff --git a/src/content/blog/2025/04/21/react-compiler-rc.md b/src/content/blog/2025/04/21/react-compiler-rc.md
new file mode 100644
index 000000000..ecbbb8747
--- /dev/null
+++ b/src/content/blog/2025/04/21/react-compiler-rc.md
@@ -0,0 +1,128 @@
+---
+title: "React Compiler RC"
+author: Lauren Tan and Mofei Zhang
+date: 2025/04/21
+description: We are releasing the compiler's first Release Candidate (RC) today.
+
+---
+
+April 21, 2025 by [Lauren Tan](https://x.com/potetotes) and [Mofei Zhang](https://x.com/zmofei).
+
+---
+
+
+
+The React team is excited to share new updates:
+
+
+
+1. We're publishing React Compiler RC today, in preparation of the compiler's stable release.
+2. We're merging `eslint-plugin-react-compiler` into `eslint-plugin-react-hooks`.
+3. We've added support for swc and are working with oxc to support Babel-free builds.
+
+---
+
+[React Compiler](https://react.dev/learn/react-compiler) is a build-time tool that optimizes your React app through automatic memoization. Last year, we published React Compiler’s [first beta](https://react.dev/blog/2024/10/21/react-compiler-beta-release) and received lots of great feedback and contributions. We’re excited about the wins we’ve seen from folks adopting the compiler (see case studies from [Sanity Studio](https://github.com/reactwg/react-compiler/discussions/33) and [Wakelet](https://github.com/reactwg/react-compiler/discussions/52)) and are working towards a stable release.
+
+We are releasing the compiler's first Release Candidate (RC) today. The RC is intended to be a stable and near-final version of the compiler, and safe to try out in production.
+
+## Use React Compiler RC today {/*use-react-compiler-rc-today*/}
+To install the RC:
+
+npm
+
+{`npm install --save-dev --save-exact babel-plugin-react-compiler@rc`}
+
+
+pnpm
+
+{`pnpm add --save-dev --save-exact babel-plugin-react-compiler@rc`}
+
+
+yarn
+
+{`yarn add --dev --exact babel-plugin-react-compiler@rc`}
+
+
+As part of the RC, we've been making React Compiler easier to add to your projects and added optimizations to how the compiler generates memoization. React Complier now supports optional chains and array indices as dependencies. We're exploring how to infer even more dependencies like equality checks and string interpolation. These improvements ultimately result in fewer re-renders and more responsive UIs.
+
+We have also heard from the community that the ref-in-render validation sometimes has false positives. Since as a general philosophy we want you to be able to fully trust in the compiler's error messages and hints, we are turning it off by default for now. We will keep working to improve this validation, and we will re-enable it in a follow up release.
+
+You can find more details on using the Compiler in [our docs](https://react.dev/learn/react-compiler).
+
+## Feedback {/*feedback*/}
+During the RC period, we encourage all React users to try the compiler and provide feedback in the React repo. Please [open an issue](https://github.com/facebook/react/issues) if you encounter any bugs or unexpected behavior. If you have a general question or suggestion, please post them in the [React Compiler Working Group](https://github.com/reactwg/react-compiler/discussions).
+
+## Backwards Compatibility {/*backwards-compatibility*/}
+As noted in the Beta announcement, React Compiler is compatible with React 17 and up. If you are not yet on React 19, you can use React Compiler by specifying a minimum target in your compiler config, and adding `react-compiler-runtime` as a dependency. You can find docs on this [here](https://react.dev/learn/react-compiler#using-react-compiler-with-react-17-or-18).
+
+## Migrating from eslint-plugin-react-compiler to eslint-plugin-react-hooks {/*migrating-from-eslint-plugin-react-compiler-to-eslint-plugin-react-hooks*/}
+If you have already installed eslint-plugin-react-compiler, you can now remove it and use `eslint-plugin-react-hooks@6.0.0-rc.1`. Many thanks to [@michaelfaith](https://bsky.app/profile/michael.faith) for contributing to this improvement!
+
+To install:
+
+npm
+
+{`npm install --save-dev eslint-plugin-react-hooks@6.0.0-rc.1`}
+
+
+pnpm
+
+{`pnpm add --save-dev eslint-plugin-react-hooks@6.0.0-rc.1`}
+
+
+yarn
+
+{`yarn add --dev eslint-plugin-react-hooks@6.0.0-rc.1`}
+
+
+```js
+// eslint.config.js
+import * as reactHooks from 'eslint-plugin-react-hooks';
+
+export default [
+ // Flat Config (eslint 9+)
+ reactHooks.configs.recommended,
+
+ // Legacy Config
+ reactHooks.configs['recommended-latest']
+];
+```
+
+To enable the React Compiler rule, add `'react-hooks/react-compiler': 'error'` to your ESLint configuration.
+
+The linter does not require the compiler to be installed, so there's no risk in upgrading eslint-plugin-react-hooks. We recommend everyone upgrade today.
+
+## swc support (experimental) {/*swc-support-experimental*/}
+React Compiler can be installed across [several build tools](/learn/react-compiler#installation) such as Babel, Vite, and Rsbuild.
+
+In addition to those tools, we have been collaborating with Kang Dongyoon ([@kdy1dev](https://x.com/kdy1dev)) from the [swc](https://swc.rs/) team on adding additional support for React Compiler as an swc plugin. While this work isn't done, Next.js build performance should now be considerably faster when the [React Compiler is enabled in your Next.js app](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler).
+
+We recommend using Next.js [15.3.1](https://github.com/vercel/next.js/releases/tag/v15.3.1) or greater to get the best build performance.
+
+Vite users can continue to use [vite-plugin-react](https://github.com/vitejs/vite-plugin-react) to enable the compiler, by adding it as a [Babel plugin](https://react.dev/learn/react-compiler#usage-with-vite). We are also working with the [oxc](https://oxc.rs/) team to [add support for the compiler](https://github.com/oxc-project/oxc/issues/10048). Once [rolldown](https://github.com/rolldown/rolldown) is officially released and supported in Vite and oxc support is added for React Compiler, we'll update the docs with information on how to migrate.
+
+## Upgrading React Compiler {/*upgrading-react-compiler*/}
+React Compiler works best when the auto-memoization applied is strictly for performance. Future versions of the compiler may change how memoization is applied, for example it could become more granular and precise.
+
+However, because product code may sometimes break the [rules of React](https://react.dev/reference/rules) in ways that aren't always statically detectable in JavaScript, changing memoization can occasionally have unexpected results. For example, a previously memoized value might be used as a dependency for a useEffect somewhere in the component tree. Changing how or whether this value is memoized can cause over or under-firing of that useEffect. While we encourage [useEffect only for synchronization](https://react.dev/learn/synchronizing-with-effects), your codebase may have useEffects that cover other use-cases such as effects that needs to only run in response to specific values changing.
+
+In other words, changing memoization may under rare circumstances cause unexpected behavior. For this reason, we recommend following the Rules of React and employing continuous end-to-end testing of your app so you can upgrade the compiler with confidence and identify any rules of React violations that might cause issues.
+
+If you don't have good test coverage, we recommend pinning the compiler to an exact version (eg `19.1.0`) rather than a SemVer range (eg `^19.1.0`). You can do this by passing the `--save-exact` (npm/pnpm) or `--exact` flags (yarn) when upgrading the compiler. You should then do any upgrades of the compiler manually, taking care to check that your app still works as expected.
+
+## Roadmap to Stable {/*roadmap-to-stable*/}
+*This is not a final roadmap, and is subject to change.*
+
+After a period of final feedback from the community on the RC, we plan on a Stable Release for the compiler.
+
+* ✅ Experimental: Released at React Conf 2024, primarily for feedback from application developers.
+* ✅ Public Beta: Available today, for feedback from library authors.
+* ✅ Release Candidate (RC): React Compiler works for the majority of rule-following apps and libraries without issue.
+* General Availability: After final feedback period from the community.
+
+Post-Stable, we plan to add more compiler optimizations and improvements. This includes both continual improvements to automatic memoization, and new optimizations altogether, with minimal to no change of product code. Each upgrade will continue to improve performance and add better handling of diverse JavaScript and React patterns.
+
+---
+
+Thanks to [Joe Savona](https://x.com/en_JS), [Jason Bonta](https://x.com/someextent), [Jimmy Lai](https://x.com/feedthejim), and [Kang Dongyoon](https://x.com/kdy1dev) (@kdy1dev) for reviewing and editing this post.
diff --git a/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md b/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md
new file mode 100644
index 000000000..e4bb25a4a
--- /dev/null
+++ b/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md
@@ -0,0 +1,14358 @@
+---
+title: "React Labs: View Transitions, Activity, and more"
+author: Ricky Hanlon
+date: 2025/04/23
+description: In React Labs posts, we write about projects in active research and development. In this post, we're sharing two new experimental features that are ready to try today, and updates on other areas we're working on now.
+---
+
+April 23, 2025 by [Ricky Hanlon](https://twitter.com/rickhanlonii)
+
+---
+
+
+
+In React Labs posts, we write about projects in active research and development. In this post, we're sharing two new experimental features that are ready to try today, and updates on other areas we're working on now.
+
+
+
+
+
+
+React Conf 2025 is scheduled for October 7–8 in Henderson, Nevada!
+
+We're looking for speakers to help us create talks about the features covered in this post. If you're interested in speaking at ReactConf, [please apply here](https://forms.reform.app/react-conf/call-for-speakers/) (no talk proposal required).
+
+For more info on tickets, free streaming, sponsoring, and more, see [the React Conf website](https://conf.react.dev).
+
+
+
+Today, we're excited to release documentation for two new experimental features that are ready for testing:
+
+- [View Transitions](#view-transitions)
+- [Activity](#activity)
+
+We're also sharing updates on new features currently in development:
+- [React Performance Tracks](#react-performance-tracks)
+- [Compiler IDE Extension](#compiler-ide-extension)
+- [Automatic Effect Dependencies](#automatic-effect-dependencies)
+- [Fragment Refs](#fragment-refs)
+- [Concurrent Stores](#concurrent-stores)
+
+---
+
+# New Experimental Features {/*new-experimental-features*/}
+
+View Transitions and Activity are now ready for testing in `react@experimental`. These features have been tested in production and are stable, but the final API may still change as we incorporate feedback.
+
+You can try them by upgrading React packages to the most recent experimental version:
+
+- `react@experimental`
+- `react-dom@experimental`
+
+Read on to learn how to use these features in your app, or check out the newly published docs:
+
+- [``](/reference/react/ViewTransition): A component that lets you activate an animation for a Transition.
+- [`addTransitionType`](/reference/react/addTransitionType): A function that allows you to specify the cause of a Transition.
+- [``](/reference/react/Activity): A component that lets you hide and show parts of the UI.
+
+## View Transitions {/*view-transitions*/}
+
+React View Transitions are a new experimental feature that makes it easier to add animations to UI transitions in your app. Under-the-hood, these animations use the new [`startViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) API available in most modern browsers.
+
+To opt-in to animating an element, wrap it in the new `` component:
+
+```js
+// "what" to animate.
+
+ animate me
+
+```
+
+This new component lets you declaratively define "what" to animate when an animation is activated.
+
+You can define "when" to animate by using one of these three triggers for a View Transition:
+
+```js
+// "when" to animate.
+
+// Transitions
+startTransition(() => setState(...));
+
+// Deferred Values
+const deferred = useDeferredValue(value);
+
+// Suspense
+ }>
+ Loading...
+
+```
+
+By default, these animations use the [default CSS animations for View Transitions](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API/Using#customizing_your_animations) applied (typically a smooth cross-fade). You can use [view transition pseudo-selectors](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API/Using#the_view_transition_pseudo-element_tree) to define "how" the animation runs. For example, you can use `*` to change the default animation for all transitions:
+
+```
+// "how" to animate.
+::view-transition-old(*) {
+ animation: 300ms ease-out fade-out;
+}
+::view-transition-new(*) {
+ animation: 300ms ease-in fade-in;
+}
+```
+
+When the DOM updates due to an animation trigger—like `startTransition`, `useDeferredValue`, or a `Suspense` fallback switching to content—React will use [declarative heuristics](/reference/react/ViewTransition#viewtransition) to automatically determine which `` components to activate for the animation. The browser will then run the animation that's defined in CSS.
+
+If you're familiar with the browser's View Transition API and want to know how React supports it, check out [How does `` Work](/reference/react/ViewTransition#how-does-viewtransition-work) in the docs.
+
+In this post, let's take a look at a few examples of how to use View Transitions.
+
+We'll start with this app, which doesn't animate any of the following interactions:
+- Click a video to view the details.
+- Click "back" to go back to the feed.
+- Type in the list to filter the videos.
+
+
+
+```js src/App.js active
+import TalkDetails from './Details'; import Home from './Home'; import {useRouter} from './router';
+
+export default function App() {
+ const {url} = useRouter();
+
+ // 🚩This version doesn't include any animations yet
+ return url === '/' ? : ;
+}
+```
+
+```js src/Details.js
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { use, Suspense } from "react";
+import { ChevronLeft } from "./Icons";
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+ }>
+
+
+
+
+ );
+}
+
+```
+
+```js src/Home.js
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+
{count} Videos }>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js
+import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {heading}
+ {isPending && }
+
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js
+import { useState } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Thumbnail({ video, children }) {
+ return (
+
+ {children}
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js
+import {
+ useState,
+ createContext,
+ use,
+ useTransition,
+ useLayoutEffect,
+ useEffect,
+} from "react";
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+export function Router({ children }) {
+ const [routerState, setRouterState] = useState({
+ pendingNav: () => {},
+ url: document.location.pathname,
+ });
+ const [isPending, startTransition] = useTransition();
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+ function navigate(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ function navigateBack(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+```
+
+```css src/styles.css
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+
+
+#### View Transitions do not replace CSS and JS driven animations {/*view-transitions-do-not-replace-css-and-js-driven-animations*/}
+
+View Transitions are meant to be used for UI transitions such as navigation, expanding, opening, or re-ordering. They are not meant to replace all the animations in your app.
+
+In our example app above, notice that there are already animations when you click the "like" button and in the Suspense fallback glimmer. These are good use cases for CSS animations because they are animating a specific element.
+
+
+
+### Animating navigations {/*animating-navigations*/}
+
+Our app includes a Suspense-enabled router, with [page transitions already marked as Transitions](/reference/react/useTransition#building-a-suspense-enabled-router), which means navigations are performed with `startTransition`:
+
+```js
+function navigate(url) {
+ startTransition(() => {
+ go(url);
+ });
+}
+```
+
+`startTransition` is a View Transition trigger, so we can add `` to animate between pages:
+
+```js
+// "what" to animate
+
+ {url === '/' ? : }
+
+```
+
+When the `url` changes, the `` and new route are rendered. Since the `` was updated inside of `startTransition`, the `` is activated for an animation.
+
+
+By default, View Transitions include the browser default cross-fade animation. Adding this to our example, we now have a cross-fade whenever we navigate between pages:
+
+
+
+```js src/App.js active
+import {unstable_ViewTransition as ViewTransition} from 'react'; import Details from './Details'; import Home from './Home'; import {useRouter} from './router';
+
+export default function App() {
+ const {url} = useRouter();
+
+ // Use ViewTransition to animate between pages.
+ // No additional CSS needed by default.
+ return (
+
+ {url === '/' ? : }
+
+ );
+}
+```
+
+```js src/Details.js hidden
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { use, Suspense } from "react";
+import { ChevronLeft } from "./Icons";
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+ }>
+
+
+
+
+ );
+}
+
+```
+
+```js src/Home.js hidden
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+ {count} Videos}>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+
+ return (
+
+
+
+ {heading}
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Thumbnail({ video, children }) {
+ return (
+
+ {children}
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js
+import {useState, createContext,use,useTransition,useLayoutEffect,useEffect} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+
+ function navigate(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+
+
+
+ const [routerState, setRouterState] = useState({
+ pendingNav: () => {},
+ url: document.location.pathname,
+ });
+
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+
+ function navigateBack(url) {
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+Since our router already updates the route using `startTransition`, this one line change to add `` activates with the default cross-fade animation.
+
+If you're curious how this works, see the docs for [How does `` work?](/reference/react/ViewTransition#how-does-viewtransition-work)
+
+
+
+#### Opting out of `` animations {/*opting-out-of-viewtransition-animations*/}
+
+In this example, we're wrapping the root of the app in `` for simplicity, but this means that all transitions in the app will be animated, which can lead to unexpected animations.
+
+To fix, we're wrapping route children with `"none"` so each page can control its own animation:
+
+```js
+// Layout.js
+
+ {children}
+
+```
+
+In practice, navigations should be done via "enter" and "exit" props, or by using Transition Types.
+
+
+
+### Customizing animations {/*customizing-animations*/}
+
+By default, `` includes the default cross-fade from the browser.
+
+To customize animations, you can provide props to the `` component to specify which animations to use, based on [how the `` activates](/reference/react/ViewTransition#props).
+
+For example, we can slow down the `default` cross fade animation:
+
+```js
+
+
+
+```
+
+And define `slow-fade` in CSS using [view transition classes](/reference/react/ViewTransition#view-transition-classes):
+
+```css
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+Now, the cross fade is slower:
+
+
+
+```js src/App.js active
+import { unstable_ViewTransition as ViewTransition } from "react";
+import Details from "./Details";
+import Home from "./Home";
+import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ // Define a default animation of .slow-fade.
+ // See animations.css for the animation definiton.
+ return (
+
+ {url === '/' ? : }
+
+ );
+}
+```
+
+```js src/Details.js hidden
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { use, Suspense } from "react";
+import { ChevronLeft } from "./Icons";
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+ }>
+
+
+
+
+ );
+}
+
+```
+
+```js src/Home.js hidden
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+ {count} Videos}>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+
+ return (
+
+
+
+ {heading}
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Thumbnail({ video, children }) {
+ return (
+
+ {children}
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {
+ useState,
+ createContext,
+ use,
+ useTransition,
+ useLayoutEffect,
+ useEffect,
+} from "react";
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+export function Router({ children }) {
+ const [routerState, setRouterState] = useState({
+ pendingNav: () => {},
+ url: document.location.pathname,
+ });
+ const [isPending, startTransition] = useTransition();
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+ function navigate(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ function navigateBack(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* Define .slow-fade using view transition classes */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+See [Styling View Transitions](/reference/react/ViewTransition#styling-view-transitions) for a full guide on styling ``.
+
+### Shared Element Transitions {/*shared-element-transitions*/}
+
+When two pages include the same element, often you want to animate it from one page to the next.
+
+To do this you can add a unique `name` to the ``:
+
+```js
+
+
+
+```
+
+Now the video thumbnail animates between the two pages:
+
+
+
+```js src/App.js
+import { unstable_ViewTransition as ViewTransition } from "react";
+import Details from "./Details";
+import Home from "./Home";
+import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ // Keeping our default slow-fade.
+ // This allows the content not in the shared
+ // element transition to cross-fade.
+ return (
+
+ {url === "/" ? : }
+
+ );
+}
+```
+
+```js src/Details.js hidden
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { use, Suspense } from "react";
+import { ChevronLeft } from "./Icons";
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+ }>
+
+
+
+
+ );
+}
+
+```
+
+```js src/Home.js hidden
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+ {count} Videos}>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+
+ return (
+
+
+
+ {heading}
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js active
+import { useState, unstable_ViewTransition as ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {
+ useState,
+ createContext,
+ use,
+ useTransition,
+ useLayoutEffect,
+ useEffect,
+} from "react";
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+export function Router({ children }) {
+ const [routerState, setRouterState] = useState({
+ pendingNav: () => {},
+ url: document.location.pathname,
+ });
+ const [isPending, startTransition] = useTransition();
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+ function navigate(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ function navigateBack(url) {
+ // Update router state in transition.
+ startTransition(() => {
+ go(url);
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* No additional animations needed */
+
+
+
+
+
+
+
+
+
+/* Previously defined animations below */
+
+
+
+
+
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+By default, React automatically generates a unique `name` for each element activated for a transition (see [How does `` work](/reference/react/ViewTransition#how-does-viewtransition-work)). When React sees a transition where a `` with a `name` is removed and a new `` with the same `name` is added, it will activate a shared element transition.
+
+For more info, see the docs for [Animating a Shared Element](/reference/react/ViewTransition#animating-a-shared-element).
+
+### Animating based on cause {/*animating-based-on-cause*/}
+
+Sometimes, you may want elements to animate differently based on how it was triggered. For this use case, we've added a new API called `addTransitionType` to specify the cause of a transition:
+
+```js {4,11}
+function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+}
+function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+}
+```
+
+With transition types, you can provide custom animations via props to ``. Let's add a shared element transition to the header for "6 Videos" and "Back":
+
+```js {4,5}
+
+ {heading}
+
+```
+
+Here we pass a `share` prop to define how to animate based on the transition type. When the share transition activates from `nav-forward`, the view transition class `slide-forward` is applied. When it's from `nav-back`, the `slide-back` animation is activated. Let's define these animations in CSS:
+
+```css
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: ...
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: ...
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: ...
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: ...
+}
+```
+
+Now we can animate the header along with thumbnail based on navigation type:
+
+
+
+```js src/App.js hidden
+import { unstable_ViewTransition as ViewTransition } from "react";
+import Details from "./Details";
+import Home from "./Home";
+import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ // Keeping our default slow-fade.
+ return (
+
+ {url === "/" ? : }
+
+ );
+}
+```
+
+```js src/Details.js hidden
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { use, Suspense } from "react";
+import { ChevronLeft } from "./Icons";
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+ }>
+
+
+
+
+ );
+}
+
+```
+
+```js src/Home.js hidden
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+ {count} Videos}>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js active
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* New keyframes to support our animations above. */
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+/* Previously defined animations. */
+
+/* Default .slow-fade. */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+### Animating Suspense Boundaries {/*animating-suspense-boundaries*/}
+
+Suspense will also activate View Transitions.
+
+To animate the fallback to content, we can wrap `Suspense` with ``:
+
+```js
+
+ }>
+
+
+
+```
+
+By adding this, the fallback will cross-fade into the content. Click a video and see the video info animate in:
+
+
+
+```js src/App.js hidden
+import { unstable_ViewTransition as ViewTransition } from "react";
+import Details from "./Details";
+import Home from "./Home";
+import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ // Default slow-fade animation.
+ return (
+
+ {url === "/" ? : }
+
+ );
+}
+```
+
+```js src/Details.js active
+import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons";
+
+function VideoDetails({ id }) {
+ // Cross-fade the fallback to content.
+ return (
+
+ }>
+
+
+
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+
+
+
+ );
+}
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+
+
{details.title}
+
{details.description}
+
+ );
+}
+```
+
+```js src/Home.js hidden
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+ {count} Videos}>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* Slide the fallback down */
+::view-transition-old(.slide-down) {
+ animation: 150ms ease-out both fade-out, 150ms ease-out both slide-down;
+}
+
+/* Slide the content up */
+::view-transition-new(.slide-up) {
+ animation: 210ms ease-in 150ms both fade-in, 400ms ease-in both slide-up;
+}
+
+/* Define the new keyframes */
+@keyframes slide-up {
+ from {
+ transform: translateY(10px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-down {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(10px);
+ }
+}
+
+/* Previously defined animations below */
+
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* Keyframes to support our animations above. */
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+/* Default .slow-fade. */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+We can also provide custom animations using an `exit` on the fallback, and `enter` on the content:
+
+```js {3,8}
+
+
+
+ }
+>
+
+
+
+
+```
+
+Here's how we'll define `slide-down` and `slide-up` with CSS:
+
+```css {1, 6}
+::view-transition-old(.slide-down) {
+ /* Slide the fallback down */
+ animation: ...;
+}
+
+::view-transition-new(.slide-up) {
+ /* Slide the content up */
+ animation: ...;
+}
+```
+
+Now, the Suspense content replaces the fallback with a sliding animation:
+
+
+
+```js src/App.js hidden
+import { unstable_ViewTransition as ViewTransition } from "react";
+import Details from "./Details";
+import Home from "./Home";
+import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ // Default slow-fade animation.
+ return (
+
+ {url === "/" ? : }
+
+ );
+}
+```
+
+```js src/Details.js active
+import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons";
+
+function VideoDetails({ id }) {
+ return (
+
+
+
+ }
+ >
+ {/* Animate the content up */}
+
+
+
+
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+
+
+
+ );
+}
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+```
+
+```js src/Home.js hidden
+import { Video } from "./Videos";
+import Layout from "./Layout";
+import { fetchVideos } from "./data";
+import { useId, useState, use } from "react";
+import { IconSearch } from "./Icons";
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState("");
+ const foundVideos = filterVideos(videos, searchText);
+ return (
+ {count} Videos}>
+
+
+ {foundVideos.length === 0 && (
+
No results
+ )}
+
+ {foundVideos.map((video) => (
+
+ ))}
+
+
+
+ );
+}
+
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* Slide the fallback down */
+::view-transition-old(.slide-down) {
+ animation: 150ms ease-out both fade-out, 150ms ease-out both slide-down;
+}
+
+/* Slide the content up */
+::view-transition-new(.slide-up) {
+ animation: 210ms ease-in 150ms both fade-in, 400ms ease-in both slide-up;
+}
+
+/* Define the new keyframes */
+@keyframes slide-up {
+ from {
+ transform: translateY(10px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-down {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(10px);
+ }
+}
+
+/* Previously defined animations below */
+
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* Keyframes to support our animations above. */
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+/* Default .slow-fade. */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+
+### Animating Lists {/*animating-lists*/}
+
+You can also use `` to animate lists of items as they re-order, like in a searchable list of items:
+
+```js {3,5}
+
+ {filteredVideos.map((video) => (
+
+
+
+ ))}
+
+```
+
+To activate the ViewTransition, we can use `useDeferredValue`:
+
+```js {2}
+const [searchText, setSearchText] = useState('');
+const deferredSearchText = useDeferredValue(searchText);
+const filteredVideos = filterVideos(videos, deferredSearchText);
+```
+
+Now the items animate as you type in the search bar:
+
+
+
+```js src/App.js hidden
+import { unstable_ViewTransition as ViewTransition } from "react";
+import Details from "./Details";
+import Home from "./Home";
+import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ // Default slow-fade animation.
+ return (
+
+ {url === "/" ? : }
+
+ );
+}
+```
+
+```js src/Details.js hidden
+import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react";
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { ChevronLeft } from "./Icons";
+
+function VideoDetails({id}) {
+ // Animate from Suspense fallback to content
+ return (
+
+
+
+ }
+ >
+ {/* Animate the content up */}
+
+
+
+
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+
+
+
+ );
+}
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+```
+
+```js src/Home.js
+import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons";
+
+function SearchList({searchText, videos}) {
+ // Activate with useDeferredValue ("when")
+ const deferredSearchText = useDeferredValue(searchText);
+ const filteredVideos = filterVideos(videos, deferredSearchText);
+ return (
+
+
+ {filteredVideos.map((video) => (
+ // Animate each item in list ("what")
+
+
+
+ ))}
+
+ {filteredVideos.length === 0 && (
+
No results
+ )}
+
+ );
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState('');
+
+ return (
+ {count} Videos}>
+
+
+
+ );
+}
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* No additional animations needed */
+
+
+
+
+
+
+
+
+
+/* Previously defined animations below */
+
+
+
+
+
+
+/* Slide animation for Suspense */
+::view-transition-old(.slide-down) {
+ animation: 150ms ease-out both fade-out, 150ms ease-out both slide-down;
+}
+
+::view-transition-new(.slide-up) {
+ animation: 210ms ease-in 150ms both fade-in, 400ms ease-in both slide-up;
+}
+
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* Keyframes to support our animations above. */
+@keyframes slide-up {
+ from {
+ transform: translateY(10px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-down {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(10px);
+ }
+}
+
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+
+/* Default .slow-fade. */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+### Final result {/*final-result*/}
+
+By adding a few `` components and a few lines of CSS, we were able to add all the animations above into the final result.
+
+We're excited about View Transitions and think they will level up the apps you're able to build. They're ready to start trying today in the experimental channel of React releases.
+
+Let's remove the slow fade, and take a look at the final result:
+
+
+
+```js src/App.js
+import {unstable_ViewTransition as ViewTransition} from 'react'; import Details from './Details'; import Home from './Home'; import {useRouter} from './router';
+
+export default function App() {
+ const {url} = useRouter();
+
+ // Animate with a cross fade between pages.
+ return (
+
+ {url === '/' ? : }
+
+ );
+}
+```
+
+```js src/Details.js
+import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons";
+
+function VideoDetails({id}) {
+ // Animate from Suspense fallback to content
+ return (
+
+
+
+ }
+ >
+ {/* Animate the content up */}
+
+
+
+
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+
+
+
+ );
+}
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+```
+
+```js src/Home.js
+import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons";
+
+function SearchList({searchText, videos}) {
+ // Activate with useDeferredValue ("when")
+ const deferredSearchText = useDeferredValue(searchText);
+ const filteredVideos = filterVideos(videos, deferredSearchText);
+ return (
+
+
+ {filteredVideos.map((video) => (
+ // Animate each item in list ("what")
+
+
+
+ ))}
+
+ {filteredVideos.length === 0 && (
+
No results
+ )}
+
+ );
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState('');
+
+ return (
+ {count} Videos}>
+
+
+
+ );
+}
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js
+import { useState, unstable_ViewTransition as ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* Slide animations for Suspense the fallback down */
+::view-transition-old(.slide-down) {
+ animation: 150ms ease-out both fade-out, 150ms ease-out both slide-down;
+}
+
+::view-transition-new(.slide-up) {
+ animation: 210ms ease-in 150ms both fade-in, 400ms ease-in both slide-up;
+}
+
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* Keyframes to support our animations above. */
+@keyframes slide-up {
+ from {
+ transform: translateY(10px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-down {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(10px);
+ }
+}
+
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+If you're curious to know more about how they work, check out [How Does `` Work](/reference/react/ViewTransition#how-does-viewtransition-work) in the docs.
+
+_For more background on how we built View Transitions, see: [#31975](https://github.com/facebook/react/pull/31975), [#32105](https://github.com/facebook/react/pull/32105), [#32041](https://github.com/facebook/react/pull/32041), [#32734](https://github.com/facebook/react/pull/32734), [#32797](https://github.com/facebook/react/pull/32797) [#31999](https://github.com/facebook/react/pull/31999), [#32031](https://github.com/facebook/react/pull/32031), [#32050](https://github.com/facebook/react/pull/32050), [#32820](https://github.com/facebook/react/pull/32820), [#32029](https://github.com/facebook/react/pull/32029), [#32028](https://github.com/facebook/react/pull/32028), and [#32038](https://github.com/facebook/react/pull/32038) by [@sebmarkbage](https://twitter.com/sebmarkbage) (thanks Seb!)._
+
+---
+
+## Activity {/*activity*/}
+
+In [past](/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022#offscreen) [updates](/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024#offscreen-renamed-to-activity), we shared that we were researching an API to allow components to be visually hidden and deprioritized, preserving UI state with reduced performance costs relative to unmounting or hiding with CSS.
+
+We're now ready to share the API and how it works, so you can start testing it in experimental React versions.
+
+`` is a new component to hide and show parts of the UI:
+
+```js [[1, 1, "'visible'"], [2, 1, "'hidden'"]]
+
+
+
+```
+
+When an Activity is visible it's rendered as normal. When an Activity is hidden it is unmounted, but will save its state and continue to render at a lower priority than anything visible on screen.
+
+You can use `Activity` to save state for parts of the UI the user isn't using, or pre-render parts that a user is likely to use next.
+
+Let's look at some examples improving the View Transition examples above.
+
+
+
+**Effects don’t mount when an Activity is hidden.**
+
+When an `` is `hidden`, Effects are unmounted. Conceptually, the component is unmounted, but React saves the state for later.
+
+In practice, this works as expected if you have followed the [You Might Not Need an Effect](/learn/you-might-not-need-an-effect) guide. To eagerly find problematic Effects, we recommend adding [``](/reference/react/StrictMode) which will eagerly perform Activity unmounts and mounts to catch any unexpected side effects.
+
+
+
+### Restoring state with Activity {/*restoring-state-with-activity*/}
+
+When a user navigates away from a page, it's common to stop rendering the old page:
+
+```js {6,7}
+function App() {
+ const { url } = useRouter();
+
+ return (
+ <>
+ {url === '/' && }
+ {url !== '/' && }
+ >
+ );
+}
+```
+
+However, this means if the user goes back to the old page, all of the previous state is lost. For example, if the ` ` page has an ` ` field, when the user leaves the page the ` ` is unmounted, and all of the text they had typed is lost.
+
+Activity allows you to keep the state around as the user changes pages, so when they come back they can resume where they left off. This is done by wrapping part of the tree in `` and toggling the `mode`:
+
+```js {6-8}
+function App() {
+ const { url } = useRouter();
+
+ return (
+ <>
+
+
+
+ {url !== '/' && }
+ >
+ );
+}
+```
+
+With this change, we can improve on our View Transitions example above. Before, when you searched for a video, selected one, and returned, your search filter was lost. With Activity, your search filter is restored and you can pick up where you left off.
+
+Try searching for a video, selecting it, and clicking "back":
+
+
+
+```js src/App.js
+import { unstable_ViewTransition as ViewTransition, unstable_Activity as Activity } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router";
+
+export default function App() {
+ const { url } = useRouter();
+
+ return (
+ // View Transitions know about Activity
+
+ {/* Render Home in Activity so we don't lose state */}
+
+
+
+ {url !== '/' && }
+
+ );
+}
+```
+
+```js src/Details.js hidden
+import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react";
+import { fetchVideo, fetchVideoDetails } from "./data";
+import { Thumbnail, VideoControls } from "./Videos";
+import { useRouter } from "./router";
+import Layout from "./Layout";
+import { ChevronLeft } from "./Icons";
+
+function VideoDetails({id}) {
+ // Animate from Suspense fallback to content
+ return (
+
+
+
+ }
+ >
+ {/* Animate the content up */}
+
+
+
+
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details() {
+ const { url, navigateBack } = useRouter();
+ const videoId = url.split("/").pop();
+ const video = use(fetchVideo(videoId));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+
+
+
+ );
+}
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+```
+
+```js src/Home.js hidden
+import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons";
+
+function SearchList({searchText, videos}) {
+ // Activate with useDeferredValue ("when")
+ const deferredSearchText = useDeferredValue(searchText);
+ const filteredVideos = filterVideos(videos, deferredSearchText);
+ return (
+
+ {filteredVideos.length === 0 && (
+
No results
+ )}
+
+ {filteredVideos.map((video) => (
+ // Animate each item in list ("what")
+
+
+
+ ))}
+
+
+ );
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState('');
+
+ return (
+ {count} Videos}>
+
+
+
+ );
+}
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* No additional animations needed */
+
+
+
+
+
+
+
+
+
+/* Previously defined animations below */
+
+
+
+
+
+
+/* Slide animations for Suspense the fallback down */
+::view-transition-old(.slide-down) {
+ animation: 150ms ease-out both fade-out, 150ms ease-out both slide-down;
+}
+
+::view-transition-new(.slide-up) {
+ animation: 210ms ease-in 150ms both fade-in, 400ms ease-in both slide-up;
+}
+
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* Keyframes to support our animations above. */
+@keyframes slide-up {
+ from {
+ transform: translateY(10px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-down {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(10px);
+ }
+}
+
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+/* Default .slow-fade. */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+### Pre-rendering with Activity {/*prerender-with-activity*/}
+
+Sometimes, you may want to prepare the next part of the UI a user is likely to use ahead of time, so it's ready by the time they are ready to use it. This is especially useful if the next route needs to suspend on data it needs to render, because you can help ensure the data is already fetched before the user navigates.
+
+For example, our app currently needs to suspend to load the data for each video when you select one. We can improve this by rendering all of the pages in a hidden `` until the user navigates:
+
+```js {2,5,8}
+
+
+
+
+
+
+
+
+
+
+
+```
+
+With this update, if the content on the next page has time to pre-render, it will animate in without the Suspense fallback. Click a video, and notice that the video title and description on the Details page render immediately, without a fallback:
+
+
+
+```js src/App.js
+import { unstable_ViewTransition as ViewTransition, unstable_Activity as Activity, use } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; import {fetchVideos} from './data'
+
+export default function App() {
+ const { url } = useRouter();
+ const videoId = url.split("/").pop();
+ const videos = use(fetchVideos());
+
+ return (
+
+ {/* Render videos in Activity to pre-render them */}
+ {videos.map(({id}) => (
+
+
+
+ ))}
+
+
+
+
+ );
+}
+```
+
+```js src/Details.js
+import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons";
+
+function VideoDetails({id}) {
+ // Animate from Suspense fallback to content.
+ // If this is pre-rendered then the fallback
+ // won't need to show.
+ return (
+
+
+
+ }
+ >
+ {/* Animate the content up */}
+
+
+
+
+ );
+}
+
+function VideoInfoFallback() {
+ return (
+ <>
+
+
+ >
+ );
+}
+
+export default function Details({id}) {
+ const { url, navigateBack } = useRouter();
+ const video = use(fetchVideo(id));
+
+ return (
+ {
+ navigateBack("/");
+ }}
+ >
+ Back
+
+ }
+ >
+
+
+
+
+
+
+
+ );
+}
+
+function VideoInfo({ id }) {
+ const details = use(fetchVideoDetails(id));
+ return (
+ <>
+ {details.title}
+ {details.description}
+ >
+ );
+}
+```
+
+```js src/Home.js hidden
+import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons";
+
+function SearchList({searchText, videos}) {
+ // Activate with useDeferredValue ("when")
+ const deferredSearchText = useDeferredValue(searchText);
+ const filteredVideos = filterVideos(videos, deferredSearchText);
+ return (
+
+ {filteredVideos.length === 0 && (
+
No results
+ )}
+
+ {filteredVideos.map((video) => (
+ // Animate each item in list ("what")
+
+
+
+ ))}
+
+
+ );
+}
+
+export default function Home() {
+ const videos = use(fetchVideos());
+ const count = videos.length;
+ const [searchText, setSearchText] = useState('');
+
+ return (
+ {count} Videos}>
+
+
+
+ );
+}
+
+function SearchInput({ value, onChange }) {
+ const id = useId();
+ return (
+
+ );
+}
+
+function filterVideos(videos, query) {
+ const keywords = query
+ .toLowerCase()
+ .split(" ")
+ .filter((s) => s !== "");
+ if (keywords.length === 0) {
+ return videos;
+ }
+ return videos.filter((video) => {
+ const words = (video.title + " " + video.description)
+ .toLowerCase()
+ .split(" ");
+ return keywords.every((kw) => words.some((w) => w.includes(kw)));
+ });
+}
+```
+
+```js src/Icons.js hidden
+export function ChevronLeft() {
+ return (
+
+
+
+
+
+
+ );
+}
+
+export function PauseIcon() {
+ return (
+
+
+
+ );
+}
+
+export function PlayIcon() {
+ return (
+
+
+
+ );
+}
+export function Heart({liked, animate}) {
+ return (
+ <>
+
+
+
+
+
+ {liked ? (
+
+ ) : (
+
+ )}
+
+ >
+ );
+}
+
+export function IconSearch(props) {
+ return (
+
+
+
+ );
+}
+```
+
+```js src/Layout.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router";
+
+export default function Page({ heading, children }) {
+ const isPending = useIsNavPending();
+ return (
+
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+ {
+ const nextIsLiked = !isLiked;
+ if (nextIsLiked) {
+ likedVideos.add(video.id);
+ } else {
+ likedVideos.delete(video.id);
+ }
+ setAnimate(true);
+ setIsLiked(nextIsLiked);
+ }}>
+
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+export function VideoControls() {
+ const [isPlaying, setIsPlaying] = useState(false);
+
+ return (
+
+ startTransition(() => {
+ setIsPlaying((p) => !p);
+ })
+ }
+ >
+ {isPlaying ? : }
+
+ );
+}
+
+export function Video({ video }) {
+ const { navigate } = useRouter();
+
+ return (
+
+
{
+ e.preventDefault();
+ navigate(`/video/${video.id}`);
+ }}
+ >
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+const videos = [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ },
+ {
+ id: '2',
+ title: 'Second video',
+ description: 'Video description',
+ image: 'red',
+ },
+ {
+ id: '3',
+ title: 'Third video',
+ description: 'Video description',
+ image: 'green',
+ },
+ {
+ id: '4',
+ title: 'Fourth video',
+ description: 'Video description',
+ image: 'purple',
+ },
+ {
+ id: '5',
+ title: 'Fifth video',
+ description: 'Video description',
+ image: 'yellow',
+ },
+ {
+ id: '6',
+ title: 'Sixth video',
+ description: 'Video description',
+ image: 'gray',
+ },
+];
+
+let videosCache = new Map();
+let videoCache = new Map();
+let videoDetailsCache = new Map();
+const VIDEO_DELAY = 1;
+const VIDEO_DETAILS_DELAY = 1000;
+export function fetchVideos() {
+ if (videosCache.has(0)) {
+ return videosCache.get(0);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos);
+ }, VIDEO_DELAY);
+ });
+ videosCache.set(0, promise);
+ return promise;
+}
+
+export function fetchVideo(id) {
+ if (videoCache.has(id)) {
+ return videoCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DELAY);
+ });
+ videoCache.set(id, promise);
+ return promise;
+}
+
+export function fetchVideoDetails(id) {
+ if (videoDetailsCache.has(id)) {
+ return videoDetailsCache.get(id);
+ }
+ const promise = new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(videos.find((video) => video.id === id));
+ }, VIDEO_DETAILS_DELAY);
+ });
+ videoDetailsCache.set(id, promise);
+ return promise;
+}
+```
+
+```js src/router.js hidden
+import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react";
+
+export function Router({ children }) {
+ const [isPending, startTransition] = useTransition();
+ const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname});
+ function navigate(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav forward"
+ addTransitionType('nav-forward');
+ go(url);
+ });
+ }
+ function navigateBack(url) {
+ startTransition(() => {
+ // Transition type for the cause "nav backward"
+ addTransitionType('nav-back');
+ go(url);
+ });
+ }
+
+ function go(url) {
+ setRouterState({
+ url,
+ pendingNav() {
+ window.history.pushState({}, "", url);
+ },
+ });
+ }
+
+ useEffect(() => {
+ function handlePopState() {
+ // This should not animate because restoration has to be synchronous.
+ // Even though it's a transition.
+ startTransition(() => {
+ setRouterState({
+ url: document.location.pathname + document.location.search,
+ pendingNav() {
+ // Noop. URL has already updated.
+ },
+ });
+ });
+ }
+ window.addEventListener("popstate", handlePopState);
+ return () => {
+ window.removeEventListener("popstate", handlePopState);
+ };
+ }, []);
+ const pendingNav = routerState.pendingNav;
+ useLayoutEffect(() => {
+ pendingNav();
+ }, [pendingNav]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+const RouterContext = createContext({ url: "/", params: {} });
+
+export function useRouter() {
+ return use(RouterContext);
+}
+
+export function useIsNavPending() {
+ return use(RouterContext).isPending;
+}
+
+```
+
+```css src/styles.css hidden
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Rg.woff2) format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Md.woff2) format("woff2");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: Optimistic Text;
+ src: url(https://react.dev/fonts/Optimistic_Text_W_Bd.woff2) format("woff2");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html {
+ background-image: url(https://react.dev/images/meta-gradient-dark.png);
+ background-size: 100%;
+ background-position: -100%;
+ background-color: rgb(64 71 86);
+ background-repeat: no-repeat;
+ height: 100%;
+ width: 100%;
+}
+
+body {
+ font-family: Optimistic Text, -apple-system, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
+ padding: 10px 0 10px 0;
+ margin: 0;
+ display: flex;
+ justify-content: center;
+}
+
+#root {
+ flex: 1 1;
+ height: auto;
+ background-color: #fff;
+ border-radius: 10px;
+ max-width: 450px;
+ min-height: 600px;
+ padding-bottom: 10px;
+}
+
+h1 {
+ margin-top: 0;
+ font-size: 22px;
+}
+
+h2 {
+ margin-top: 0;
+ font-size: 20px;
+}
+
+h3 {
+ margin-top: 0;
+ font-size: 18px;
+}
+
+h4 {
+ margin-top: 0;
+ font-size: 16px;
+}
+
+h5 {
+ margin-top: 0;
+ font-size: 14px;
+}
+
+h6 {
+ margin-top: 0;
+ font-size: 12px;
+}
+
+code {
+ font-size: 1.2em;
+}
+
+ul {
+ padding-inline-start: 20px;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.absolute {
+ position: absolute;
+}
+
+.overflow-visible {
+ overflow: visible;
+}
+
+.visible {
+ overflow: visible;
+}
+
+.fit {
+ width: fit-content;
+}
+
+
+/* Layout */
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.top-hero {
+ height: 200px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-image: conic-gradient(
+ from 90deg at -10% 100%,
+ #2b303b 0deg,
+ #2b303b 90deg,
+ #16181d 1turn
+ );
+}
+
+.bottom {
+ flex: 1;
+ overflow: auto;
+}
+
+.top-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0;
+ padding: 0 12px;
+ top: 0;
+ width: 100%;
+ height: 44px;
+ color: #23272f;
+ font-weight: 700;
+ font-size: 20px;
+ z-index: 100;
+ cursor: default;
+}
+
+.content {
+ padding: 0 12px;
+ margin-top: 4px;
+}
+
+
+.loader {
+ color: #23272f;
+ font-size: 3px;
+ width: 1em;
+ margin-right: 18px;
+ height: 1em;
+ border-radius: 50%;
+ position: relative;
+ text-indent: -9999em;
+ animation: loading-spinner 1.3s infinite linear;
+ animation-delay: 200ms;
+ transform: translateZ(0);
+}
+
+@keyframes loading-spinner {
+ 0%,
+ 100% {
+ box-shadow: 0 -3em 0 0.2em,
+ 2em -2em 0 0em, 3em 0 0 -1em,
+ 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 0;
+ }
+ 12.5% {
+ box-shadow: 0 -3em 0 0, 2em -2em 0 0.2em,
+ 3em 0 0 0, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 25% {
+ box-shadow: 0 -3em 0 -0.5em,
+ 2em -2em 0 0, 3em 0 0 0.2em,
+ 2em 2em 0 0, 0 3em 0 -1em,
+ -2em 2em 0 -1em, -3em 0 0 -1em,
+ -2em -2em 0 -1em;
+ }
+ 37.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 0, 2em 2em 0 0.2em, 0 3em 0 0em,
+ -2em 2em 0 -1em, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 50% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 0em, 0 3em 0 0.2em,
+ -2em 2em 0 0, -3em 0em 0 -1em, -2em -2em 0 -1em;
+ }
+ 62.5% {
+ box-shadow: 0 -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 0,
+ -2em 2em 0 0.2em, -3em 0 0 0, -2em -2em 0 -1em;
+ }
+ 75% {
+ box-shadow: 0em -3em 0 -1em, 2em -2em 0 -1em,
+ 3em 0em 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0.2em, -2em -2em 0 0;
+ }
+ 87.5% {
+ box-shadow: 0em -3em 0 0, 2em -2em 0 -1em,
+ 3em 0 0 -1em, 2em 2em 0 -1em, 0 3em 0 -1em,
+ -2em 2em 0 0, -3em 0em 0 0, -2em -2em 0 0.2em;
+ }
+}
+
+/* LikeButton */
+.like-button {
+ outline-offset: 2px;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ cursor: pointer;
+ border-radius: 9999px;
+ border: none;
+ outline: none 2px;
+ color: #5e687e;
+ background: none;
+}
+
+.like-button:focus {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+}
+
+.like-button:active {
+ color: #a6423a;
+ background-color: rgba(166, 66, 58, .05);
+ transform: scaleX(0.95) scaleY(0.95);
+}
+
+.like-button:hover {
+ background-color: #f6f7f9;
+}
+
+.like-button.liked {
+ color: #a6423a;
+}
+
+/* Icons */
+@keyframes circle {
+ 0% {
+ transform: scale(0);
+ stroke-width: 16px;
+ }
+
+ 50% {
+ transform: scale(.5);
+ stroke-width: 16px;
+ }
+
+ to {
+ transform: scale(1);
+ stroke-width: 0;
+ }
+}
+
+.circle {
+ color: rgba(166, 66, 58, .5);
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4,0,.2,1);
+}
+
+.circle.liked.animate {
+ animation: circle .3s forwards;
+}
+
+.heart {
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.heart.liked {
+ transform-origin: center;
+ transition-property: all;
+ transition-duration: .15s;
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+.heart.liked.animate {
+ animation: scale .35s ease-in-out forwards;
+}
+
+.control-icon {
+ color: hsla(0, 0%, 100%, .5);
+ filter: drop-shadow(0 20px 13px rgba(0, 0, 0, .03)) drop-shadow(0 8px 5px rgba(0, 0, 0, .08));
+}
+
+.chevron-left {
+ margin-top: 2px;
+ rotate: 90deg;
+}
+
+
+/* Video */
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+
+.thumbnail.red {
+ background-image: conic-gradient(at top right, #c76a15, #a6423a, #2b3491);
+}
+
+.thumbnail.green {
+ background-image: conic-gradient(at top right, #c76a15, #388f7f, #2b3491);
+}
+
+.thumbnail.purple {
+ background-image: conic-gradient(at top right, #c76a15, #575fb7, #2b3491);
+}
+
+.thumbnail.yellow {
+ background-image: conic-gradient(at top right, #c76a15, #FABD62, #2b3491);
+}
+
+.thumbnail.gray {
+ background-image: conic-gradient(at top right, #c76a15, #4E5769, #2b3491);
+}
+
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+}
+
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+
+.video .info:hover {
+ text-decoration: underline;
+}
+
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+
+/* Details */
+.details .thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 100%;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+
+.video-details-title {
+ margin-top: 8px;
+}
+
+.video-details-speaker {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px
+}
+
+.back {
+ display: flex;
+ align-items: center;
+ margin-left: -5px;
+ cursor: pointer;
+}
+
+.back:hover {
+ text-decoration: underline;
+}
+
+.info-title {
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.25;
+ margin: 8px 0 0 0 ;
+}
+
+.info-description {
+ margin: 8px 0 0 0;
+}
+
+.controls {
+ cursor: pointer;
+}
+
+.fallback {
+ background: #f6f7f8 linear-gradient(to right, #e6e6e6 5%, #cccccc 25%, #e6e6e6 35%) no-repeat;
+ background-size: 800px 104px;
+ display: block;
+ line-height: 1.25;
+ margin: 8px 0 0 0;
+ border-radius: 5px;
+ overflow: hidden;
+
+ animation: 1s linear 1s infinite shimmer;
+ animation-delay: 300ms;
+ animation-duration: 1s;
+ animation-fill-mode: forwards;
+ animation-iteration-count: infinite;
+ animation-name: shimmer;
+ animation-timing-function: linear;
+}
+
+
+.fallback.title {
+ width: 130px;
+ height: 30px;
+
+}
+
+.fallback.description {
+ width: 150px;
+ height: 21px;
+}
+
+@keyframes shimmer {
+ 0% {
+ background-position: -468px 0;
+ }
+
+ 100% {
+ background-position: 468px 0;
+ }
+}
+
+.search {
+ margin-bottom: 10px;
+}
+.search-input {
+ width: 100%;
+ position: relative;
+}
+
+.search-icon {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ inset-inline-start: 0;
+ display: flex;
+ align-items: center;
+ padding-inline-start: 1rem;
+ pointer-events: none;
+ color: #99a1b3;
+}
+
+.search-input input {
+ display: flex;
+ padding-inline-start: 2.75rem;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ width: 100%;
+ text-align: start;
+ background-color: rgb(235 236 240);
+ outline: 2px solid transparent;
+ cursor: pointer;
+ border: none;
+ align-items: center;
+ color: rgb(35 39 47);
+ border-radius: 9999px;
+ vertical-align: middle;
+ font-size: 15px;
+}
+
+.search-input input:hover, .search-input input:active {
+ background-color: rgb(235 236 240/ 0.8);
+ color: rgb(35 39 47/ 0.8);
+}
+
+/* Home */
+.video-list {
+ position: relative;
+}
+
+.video-list .videos {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ overflow-y: auto;
+ height: 100%;
+}
+```
+
+
+```css src/animations.css
+/* No additional animations needed */
+
+
+
+
+
+
+
+
+
+/* Previously defined animations below */
+
+
+
+
+
+
+/* Slide animations for Suspense the fallback down */
+::view-transition-old(.slide-down) {
+ animation: 150ms ease-out both fade-out, 150ms ease-out both slide-down;
+}
+
+::view-transition-new(.slide-up) {
+ animation: 210ms ease-in 150ms both fade-in, 400ms ease-in both slide-up;
+}
+
+/* Animations for view transition classed added by transition type */
+::view-transition-old(.slide-forward) {
+ /* when sliding forward, the "old" page should slide out to left. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
+}
+
+::view-transition-new(.slide-forward) {
+ /* when sliding forward, the "new" page should slide in from right. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
+}
+
+::view-transition-old(.slide-back) {
+ /* when sliding back, the "old" page should slide out to right. */
+ animation: 150ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-right;
+}
+
+::view-transition-new(.slide-back) {
+ /* when sliding back, the "new" page should slide in from left. */
+ animation: 210ms cubic-bezier(0, 0, 0.2, 1) 150ms both fade-in,
+ 400ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-left;
+}
+
+/* Keyframes to support our animations above. */
+@keyframes slide-up {
+ from {
+ transform: translateY(10px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-down {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(10px);
+ }
+}
+
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes fade-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes slide-to-right {
+ to {
+ transform: translateX(50px);
+ }
+}
+
+@keyframes slide-from-right {
+ from {
+ transform: translateX(50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-to-left {
+ to {
+ transform: translateX(-50px);
+ }
+}
+
+@keyframes slide-from-left {
+ from {
+ transform: translateX(-50px);
+ }
+ to {
+ transform: translateX(0);
+ }
+}
+
+/* Default .slow-fade. */
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+```js src/index.js hidden
+import React, {StrictMode} from 'react';
+import {createRoot} from 'react-dom/client';
+import './styles.css';
+import './animations.css';
+
+import App from './App';
+import {Router} from './router';
+
+const root = createRoot(document.getElementById('root'));
+root.render(
+
+
+
+
+
+);
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+### Server-Side Rendering with Activity {/*server-side-rendering-with-activity*/}
+
+When using Activity on a page that uses server-side rendering (SSR), there are additional optimizations.
+
+If part of the page is rendered with `mode="hidden"`, then it will not be included in the SSR response. Instead, React will schedule a client render for the content inside Activity while the rest of the page hydrates, prioritizing the visible content on screen.
+
+For parts of the UI rendered with `mode="visible"`, React will de-prioritize hydration of content within Activity, similar to how Suspense content is hydrated at a lower priority. If the user interacts with the page, we'll prioritize hydration within the boundary if needed.
+
+These are advanced use cases, but they show the additional benefits considered with Activity.
+
+### Future modes for Activity {/*future-modes-for-activity*/}
+
+In the future, we may add more modes to Activity.
+
+For example, a common use case is rendering a modal, where the previous "inactive" page is visible behind the "active" modal view. The "hidden" mode does not work for this use case because it's not visible and not included in SSR.
+
+Instead, we're considering a new mode that would keep the content visible—and included in SSR—but keep it unmounted and de-prioritize updates. This mode may also need to "pause" DOM updates, since it can be distracting to see backgrounded content updating while a modal is open.
+
+Another mode we're considering for Activity is the ability to automatically destroy state for hidden Activities if there is too much memory being used. Since the component is already unmounted, it may be preferable to destroy state for the least recently used hidden parts of the app rather than consume too many resources.
+
+These are areas we're still exploring, and we'll share more as we make progress. For more information on what Activity includes today, [check out the docs](/reference/react/Activity).
+
+---
+
+# Features in development {/*features-in-development*/}
+
+We're also developing features to help solve the common problems below.
+
+As we iterate on possible solutions, you may see some potential APIs we're testing being shared based on the PRs we are landing. Please keep in mind that as we try different ideas, we often change or remove different solutions after trying them out.
+
+When the solutions we're working on are shared too early, it can create churn and confusion in the community. To balance being transparent and limiting confusion, we're sharing the problems we're currently developing solutions for, without sharing a particular solution we have in mind.
+
+As these features progress, we'll announce them on the blog with docs included so you can try them out.
+
+## React Performance Tracks {/*react-performance-tracks*/}
+
+We're working on a new set of custom tracks to performance profilers using browser APIs that [allow adding custom tracks](https://developer.chrome.com/docs/devtools/performance/extension) to provide more information about the performance of your React app.
+
+This feature is still in progress, so we're not ready to publish docs to fully release it as an experimental feature yet. You can get a sneak preview when using an experimental version of React, which will automatically add the performance tracks to profiles:
+
+
+
+
+
+
+
+
+
+
+
+
+There are a few known issues we plan to address such as performance, and the scheduler track not always "connecting" work across Suspended trees, so it's not quite ready to try. We're also still collecting feedback from early adopters to improve the design and usability of the tracks.
+
+Once we solve those issues, we'll publish experimental docs and share that it's ready to try.
+
+---
+
+## Automatic Effect Dependencies {/*automatic-effect-dependencies*/}
+
+When we released hooks, we had three motivations:
+
+- **Sharing code between components**: hooks replaced patterns like render props and higher-order components to allow you to reuse stateful logic without changing your component hierarchy.
+- **Think in terms of function, not lifecycles**: hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.
+- **Support ahead-of-time compilation**: hooks were designed to support ahead-of-time compilation with less pitfalls causing unintentional de-optimizations caused by lifecycle methods, and limitations of classes.
+
+Since their release, hooks have been successful at *sharing code between components*. Hooks are now the favored way to share logic between components, and there are less use cases for render props and higher order components. Hooks have also been successful at supporting features like Fast Refresh that were not possible with class components.
+
+### Effects can be hard {/*effects-can-be-hard*/}
+
+Unfortunately, some hooks are still hard to think in terms of function instead of lifecycles. Effects specifically are still hard to understand and are the most common pain point we hear from developers. Last year, we spent a significant amount of time researching how Effects were used, and how those use cases could be simplified and easier to understand.
+
+We found that often, the confusion is from using an Effect when you don't need to. The [You Might Not Need an Effect](/learn/you-might-not-need-an-effect) guide covers many cases for when Effects are not the right solution. However, even when an Effect is the right fit for a problem, Effects can still be harder to understand than class component lifecycles.
+
+We believe one of the reasons for confusion is that developers to think of Effects from the _component's_ perspective (like a lifecycle), instead of the _Effects_ point of view (what the Effect does).
+
+Let's look at an example [from the docs](/learn/lifecycle-of-reactive-effects#thinking-from-the-effects-perspective):
+
+```js
+useEffect(() => {
+ // Your Effect connected to the room specified with roomId...
+ const connection = createConnection(serverUrl, roomId);
+ connection.connect();
+ return () => {
+ // ...until it disconnected
+ connection.disconnect();
+ };
+}, [roomId]);
+```
+
+Many users would read this code as "on mount, connect to the roomId. whenever `roomId` changes, disconnect to the old room and re-create the connection". However, this is thinking from the component's lifecycle perspective, which means you will need to think of every component lifecycle state to write the Effect correctly. This can be difficult, so it's understandable that Effects seem harder than class lifecycles when using the component perspective.
+
+### Effects without dependencies {/*effects-without-dependencies*/}
+
+Instead, it's better to think from the Effect's perspective. The Effect doesn't know about the component lifecycles. It only describes how to start synchronization and how to stop it. When users think of Effects in this way, their Effects tend to be easier to write, and more resilient to being started and stopped as many times as is needed.
+
+We spent some time researching why Effects are thought of from the component perspective, and we think one of the reasons is the dependency array. Since you have to write it, it's right there and in your face reminding you of what you're "reacting" to and baiting you into the mental model of 'do this when these values change'.
+
+When we released hooks, we knew we could make them easier to use with ahead-of-time compilation. With the React Compiler, you're now able to avoid writing `useCallback` and `useMemo` yourself in most cases. For Effects, the compiler can insert the dependencies for you:
+
+```js
+useEffect(() => {
+ const connection = createConnection(serverUrl, roomId);
+ connection.connect();
+ return () => {
+ connection.disconnect();
+ };
+}); // compiler inserted dependencies.
+```
+
+With this code, the React Compiler can infer the dependencies for you and insert them automatically so you don't need to see or write them. With features like [the IDE extension](#compiler-ide-extension) and [`useEffectEvent`](/reference/react/experimental_useEffectEvent), we can provide a CodeLens to show you what the Compiler inserted for times you need to debug, or to optimize by removing a dependency. This helps reinforce the correct mental model for writing Effects, which can run at any time to synchronize your component or hook's state with something else.
+
+Our hope is that automatically inserting dependencies is not only easier to write, but that it also makes them easier to understand by forcing you to think in terms of what the Effect does, and not in component lifecycles.
+
+---
+
+## Compiler IDE Extension {/*compiler-ide-extension*/}
+
+Earlier this week [we shared](/blog/2025/04/21/react-compiler-rc) the React Compiler release candidate, and we're working towards shipping the first SemVer stable version of the compiler in the coming months.
+
+We've also begun exploring ways to use the React Compiler to provide information that can improve understanding and debugging your code. One idea we've started exploring is a new experimental LSP-based React IDE extension powered by React Compiler, similar to the extension used in [Lauren Tan's React Conf talk](https://conf2024.react.dev/talks/5).
+
+Our idea is that we can use the compiler's static analysis to provide more information, suggestions, and optimization opportunities directly in your IDE. For example, we can provide diagnostics for code breaking the Rules of React, hovers to show if components and hooks were optimized by the compiler, or a CodeLens to see [automatically inserted Effect dependencies](#automatic-effect-dependencies).
+
+The IDE extension is still an early exploration, but we'll share our progress in future updates.
+
+---
+
+## Fragment Refs {/*fragment-refs*/}
+
+Many DOM APIs like those for event management, positioning, and focus are difficult to compose when writing with React. This often leads developers to reach for Effects, managing multiple Refs, by using APIs like `findDOMNode` (removed in React 19).
+
+We are exploring adding refs to Fragments that would point to a group of DOM elements, rather than just a single element. Our hope is that this will simplify managing multiple children and make it easier to write composable React code when calling DOM APIs.
+
+Fragment refs are still being researched. We'll share more when we're closer to having the final API finished.
+
+---
+
+## Gesture Animations {/*gesture-animations*/}
+
+We're also researching ways to enhance View Transitions to support gesture animations such as swiping to open a menu, or scroll through a photo carousel.
+
+Gestures present new challenges for a few reasons:
+
+- **Gestures are continuous**: as you swipe the animation is tied to your finger placement time, rather than triggering and running to completion.
+- **Gestures don't complete**: when you release your finger gesture animations can run to completion, or revert to their original state (like when you only partially open a menu) depending on how far you go.
+- **Gestures invert old and new**: while you're animating, you want the page you are animating from to stay "alive" and interactive. This inverts the browser View Transition model where the "old" state is a snapshot and the "new" state is the live DOM.
+
+We believe we’ve found an approach that works well and may introduce a new API for triggering gesture transitions. For now, we're focused on shipping ``, and will revisit gestures afterward.
+
+---
+
+## Concurrent Stores {/*concurrent-stores*/}
+
+When we released React 18 with concurrent rendering, we also released `useSyncExternalStore` so external store libraries that did not use React state or context could [support concurrent rendering](https://github.com/reactwg/react-18/discussions/70) by forcing a synchronous render when the store is updated.
+
+Using `useSyncExternalStore` comes at a cost though, since it forces a bail out from concurrent features like transitions, and forces existing content to show Suspense fallbacks.
+
+Now that React 19 has shipped, we're revisiting this problem space to create a primitive to fully support concurrent external stores with the `use` API:
+
+```js
+const value = use(store);
+```
+
+Our goal is to allow external state to be read during render without tearing, and to work seamlessly with all of the concurrent features React offers.
+
+This research is still early. We'll share more, and what the new APIs will look like, when we're further along.
+
+---
+
+_Thanks to [Aurora Scharff](https://bsky.app/profile/aurorascharff.no), [Dan Abramov](https://bsky.app/profile/danabra.mov), [Eli White](https://twitter.com/Eli_White), [Lauren Tan](https://bsky.app/profile/no.lol), [Luna Wei](https://github.com/lunaleaps), [Matt Carroll](https://twitter.com/mattcarrollcode), [Jack Pope](https://jackpope.me), [Jason Bonta](https://threads.net/someextent), [Jordan Brown](https://github.com/jbrown215), [Jordan Eldredge](https://bsky.app/profile/capt.dev), [Mofei Zhang](https://threads.net/z_mofei), [Sebastien Lorber](https://bsky.app/profile/sebastienlorber.com), [Sebastian Markbåge](https://bsky.app/profile/sebmarkbage.calyptus.eu), and [Tim Yung](https://github.com/yungsters) for reviewing this post._
diff --git a/src/content/blog/index.md b/src/content/blog/index.md
index f7bbe76f3..a7a897634 100644
--- a/src/content/blog/index.md
+++ b/src/content/blog/index.md
@@ -4,7 +4,7 @@ title: React Blog
-This blog is the official source for the updates from the React team. Anything important, including release notes or deprecation notices, will be posted here first.
+This blog is the official source for the updates from the React team. Anything important, including release notes or deprecation notices, will be posted here first.
You can also follow the [@react.dev](https://bsky.app/profile/react.dev) account on Bluesky, or [@reactjs](https://twitter.com/reactjs) account on Twitter, but you won’t miss anything essential if you only read this blog.
@@ -12,7 +12,19 @@ You can also follow the [@react.dev](https://bsky.app/profile/react.dev) account
-
+
+
+In React Labs posts, we write about projects in active research and development. In this post, we're sharing two new experimental features that are ready to try today, and sharing other areas we're working on now ...
+
+
+
+
+
+We are releasing the compiler's first Release Candidate (RC) today.
+
+
+
+
Today, we’re deprecating Create React App for new apps, and encouraging existing apps to migrate to a framework, or to migrate to a build tool like Vite, Parcel, or RSBuild. We’re also providing docs for when a framework isn’t a good fit for your project, you want to build your own framework, or you just want to learn how React works by building a React app from scratch ...
diff --git a/src/content/community/conferences.md b/src/content/community/conferences.md
index 17dd96159..a97f3d5b4 100644
--- a/src/content/community/conferences.md
+++ b/src/content/community/conferences.md
@@ -25,6 +25,11 @@ May 27 - 31, 2025. In-person in Athens, Greece
[Website](https://athens.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social)
+### React Norway 2025 {/*react-norway-2025*/}
+June 13, 2025. In-person in Oslo, Norway + remote (virtual event)
+
+[Website](https://reactnorway.com/) - [Twitter](https://x.com/ReactNorway)
+
### React Summit 2025 {/*react-summit-2025*/}
June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event)
@@ -40,6 +45,11 @@ September 2-4, 2025. Wrocław, Poland.
[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/)
+### React Alicante 2025 {/*react-alicante-2025*/}
+October 2-4, 2025. Alicante, Spain.
+
+[Website](https://reactalicante.es/) - [Twitter](https://x.com/ReactAlicante) - [Bluesky](https://bsky.app/profile/reactalicante.es) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w)
+
### React Conf 2025 {/*react-conf-2025*/}
October 7-8, 2025. Henderson, Nevada, USA and free livestream
@@ -50,6 +60,16 @@ October 31 - November 01, 2025. In-person in Goa, India (hybrid event) + Oct 15
[Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Youtube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w)
+### React Summit US 2025 {/*react-summit-us-2025*/}
+November 18 - 21, 2025. In-person in New York, USA + remote (hybrid event)
+
+[Website](https://reactsummit.us/) - [Twitter](https://x.com/reactsummit)
+
+### React Advanced London 2025 {/*react-advanced-london-2025*/}
+November 28 & December 1, 2025. In-person in London, UK + online (hybrid event)
+
+[Website](https://reactadvanced.com/) - [Twitter](https://x.com/reactadvanced)
+
## Past Conferences {/*past-conferences*/}
diff --git a/src/content/community/index.md b/src/content/community/index.md
index 1e28a27f0..cf8f9323b 100644
--- a/src/content/community/index.md
+++ b/src/content/community/index.md
@@ -29,4 +29,4 @@ Each community consists of many thousands of React users.
## News {/*news*/}
-For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs) and the [official React blog](/blog/) on this website.
+For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs), [**@react.dev** on Bluesky](https://bsky.app/profile/react.dev) and the [official React blog](/blog/) on this website.
diff --git a/src/content/community/meetups.md b/src/content/community/meetups.md
index 186740341..b4da5cdff 100644
--- a/src/content/community/meetups.md
+++ b/src/content/community/meetups.md
@@ -38,7 +38,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet
## Canada {/*canada*/}
* [Halifax, NS](https://www.meetup.com/Halifax-ReactJS-Meetup/)
-* [Montreal, QC - React Native](https://www.meetup.com/fr-FR/React-Native-MTL/)
+* [Montreal, QC](https://guild.host/react-montreal/)
* [Vancouver, BC](https://www.meetup.com/ReactJS-Vancouver-Meetup/)
* [Ottawa, ON](https://www.meetup.com/Ottawa-ReactJS-Meetup/)
* [Saskatoon, SK](https://www.meetup.com/saskatoon-react-meetup/)
@@ -88,6 +88,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet
* [Delhi NCR](https://www.meetup.com/React-Delhi-NCR/)
* [Mumbai](https://reactmumbai.dev)
* [Pune](https://www.meetup.com/ReactJS-and-Friends/)
+* [Rajasthan](https://reactrajasthan.com)
## Indonesia {/*indonesia*/}
* [Indonesia](https://www.meetup.com/reactindonesia/)
diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md
index e5b396c7e..015c5848c 100644
--- a/src/content/learn/build-a-react-app-from-scratch.md
+++ b/src/content/learn/build-a-react-app-from-scratch.md
@@ -116,7 +116,7 @@ Similarly, if you rely on the apps using your framework to split the code, you m
Splitting code by route, when integrated with bundling and data fetching, can reduce the initial load time of your app and the time it takes for the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)).
For code-splitting instructions, see your build tool docs:
-- [Vite build optimizations](https://v3.vitejs.dev/guide/features.html#build-optimizations)
+- [Vite build optimizations](https://vite.dev/guide/features.html#build-optimizations)
- [Parcel code splitting](https://parceljs.org/features/code-splitting/)
- [Rsbuild code splitting](https://rsbuild.dev/guide/optimization/code-splitting)
diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md
index 1382d14ec..e4fcad6b9 100644
--- a/src/content/learn/creating-a-react-app.md
+++ b/src/content/learn/creating-a-react-app.md
@@ -32,7 +32,7 @@ This allows you to start with a client-only app, and if your needs change later,
npx create-next-app@latest
-Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any Node.js or serverless hosting, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn't require a server. Vercel additionally provides opt-in paid cloud services.
+Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any hosting provider that supports Node.js or Docker containers, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn't require a server.
### React Router (v7) {/*react-router-v7*/}
@@ -106,7 +106,7 @@ If your app has constraints not well-served by existing frameworks, you prefer t
Starting from scratch gives you more flexibility, but does require that you make choices on which tools to use for routing, data fetching, and other common usage patterns. It's a lot like building your own framework, instead of using a framework that already exists. The [frameworks we recommend](#recommended-react-frameworks) have built-in solutions for these problems.
-If you want to build your own solutions, see our guide to [build a React app from Scratch](/learn/build-a-react-app-from-scratch) for instructions on how to set up a new React project starting with a built tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/).
+If you want to build your own solutions, see our guide to [build a React app from Scratch](/learn/build-a-react-app-from-scratch) for instructions on how to set up a new React project starting with a build tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/).
-----
diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md
index 6d4f55763..70049e58e 100644
--- a/src/content/learn/keeping-components-pure.md
+++ b/src/content/learn/keeping-components-pure.md
@@ -175,7 +175,7 @@ function Cup({ guest }) {
}
export default function TeaGathering() {
- let cups = [];
+ const cups = [];
for (let i = 1; i <= 12; i++) {
cups.push( );
}
@@ -245,7 +245,7 @@ Rendering is a *calculation*, it shouldn't try to "do" things. Can you express t
```js src/Clock.js active
export default function Clock({ time }) {
- let hours = time.getHours();
+ const hours = time.getHours();
if (hours >= 0 && hours <= 6) {
document.getElementById('time').className = 'night';
} else {
@@ -307,7 +307,7 @@ You can fix this component by calculating the `className` and including it in th
```js src/Clock.js active
export default function Clock({ time }) {
- let hours = time.getHours();
+ const hours = time.getHours();
let className;
if (hours >= 0 && hours <= 6) {
className = 'night';
@@ -606,14 +606,14 @@ export default function StoryTray({ stories }) {
import { useState, useEffect } from 'react';
import StoryTray from './StoryTray.js';
-let initialStories = [
+const initialStories = [
{id: 0, label: "Ankit's Story" },
{id: 1, label: "Taylor's Story" },
];
export default function App() {
- let [stories, setStories] = useState([...initialStories])
- let time = useTime();
+ const [stories, setStories] = useState([...initialStories])
+ const time = useTime();
// HACK: Prevent the memory from growing forever while you read docs.
// We're breaking our own rules here.
@@ -702,14 +702,14 @@ export default function StoryTray({ stories }) {
import { useState, useEffect } from 'react';
import StoryTray from './StoryTray.js';
-let initialStories = [
+const initialStories = [
{id: 0, label: "Ankit's Story" },
{id: 1, label: "Taylor's Story" },
];
export default function App() {
- let [stories, setStories] = useState([...initialStories])
- let time = useTime();
+ const [stories, setStories] = useState([...initialStories])
+ const time = useTime();
// HACK: Prevent the memory from growing forever while you read docs.
// We're breaking our own rules here.
@@ -770,7 +770,7 @@ Alternatively, you could create a _new_ array (by copying the existing one) befo
```js src/StoryTray.js active
export default function StoryTray({ stories }) {
// Copy the array!
- let storiesToDisplay = stories.slice();
+ const storiesToDisplay = stories.slice();
// Does not affect the original array:
storiesToDisplay.push({
@@ -794,14 +794,14 @@ export default function StoryTray({ stories }) {
import { useState, useEffect } from 'react';
import StoryTray from './StoryTray.js';
-let initialStories = [
+const initialStories = [
{id: 0, label: "Ankit's Story" },
{id: 1, label: "Taylor's Story" },
];
export default function App() {
- let [stories, setStories] = useState([...initialStories])
- let time = useTime();
+ const [stories, setStories] = useState([...initialStories])
+ const time = useTime();
// HACK: Prevent the memory from growing forever while you read docs.
// We're breaking our own rules here.
diff --git a/src/content/learn/managing-state.md b/src/content/learn/managing-state.md
index 93bcc10fd..ef7b76e04 100644
--- a/src/content/learn/managing-state.md
+++ b/src/content/learn/managing-state.md
@@ -741,9 +741,9 @@ export default function Section({ children }) {
const level = useContext(LevelContext);
return (
);
}
@@ -836,13 +836,11 @@ export function TasksProvider({ children }) {
);
return (
-
-
+
+
{children}
-
-
+
+
);
}
diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md
index d35071845..11d398d23 100644
--- a/src/content/learn/preserving-and-resetting-state.md
+++ b/src/content/learn/preserving-and-resetting-state.md
@@ -672,7 +672,7 @@ label {
-The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `div` to a `section`. When the child `div` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well.
+The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `section` to a `div`. When the child `section` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well.
@@ -2011,7 +2011,7 @@ export default function ContactList() {
{
setReverse(e.target.checked)
}}
@@ -2110,7 +2110,7 @@ export default function ContactList() {
{
setReverse(e.target.checked)
}}
diff --git a/src/content/learn/react-compiler.md b/src/content/learn/react-compiler.md
index 7c46673e7..9d4e19d21 100644
--- a/src/content/learn/react-compiler.md
+++ b/src/content/learn/react-compiler.md
@@ -6,10 +6,6 @@ title: React Compiler
This page will give you an introduction to React Compiler and how to try it out successfully.
-
-These docs are still a work in progress. More documentation is available in the [React Compiler Working Group repo](https://github.com/reactwg/react-compiler/discussions), and will be upstreamed into these docs when they are more stable.
-
-
* Getting started with the compiler
@@ -19,25 +15,25 @@ These docs are still a work in progress. More documentation is available in the
-React Compiler is a new compiler currently in Beta, that we've open sourced to get early feedback from the community. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you’ve followed the [Rules of React](/reference/rules).
+React Compiler is a new compiler currently in RC, that we've open sourced to get feedback from the community. We now recommend everyone to try the compiler and provide feedback.
-The latest Beta release can be found with the `@beta` tag, and daily experimental releases with `@experimental`.
+The latest RC release can be found with the `@rc` tag, and daily experimental releases with `@experimental`.
-React Compiler is a new compiler that we've open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it.
+React Compiler is a new compiler that we've open sourced to get feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it.
-The compiler also includes an [ESLint plugin](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. **We strongly recommend everyone use the linter today.** The linter does not require that you have the compiler installed, so you can use it even if you are not ready to try out the compiler.
+eslint-plugin-react-hooks also includes an [ESLint rule](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. **We strongly recommend everyone use the linter today.** The linter does not require that you have the compiler installed, so you can use it even if you are not ready to try out the compiler.
-The compiler is currently released as `beta`, and is available to try out on React 17+ apps and libraries. To install the Beta:
+The compiler is currently released as `rc`, and is available to try out on React 17+ apps and libraries. To install the RC:
-npm install -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta
+{`npm install -D babel-plugin-react-compiler@rc eslint-plugin-react-hooks@^6.0.0-rc.1`}
Or, if you're using Yarn:
-yarn add -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta
+{`yarn add -D babel-plugin-react-compiler@rc eslint-plugin-react-hooks@^6.0.0-rc.1`}
If you are not using React 19 yet, please see [the section below](#using-react-compiler-with-react-17-or-18) for further instructions.
@@ -116,7 +112,7 @@ So if `expensivelyProcessAReallyLargeArrayOfObjects` was used in many different
### Should I try out the compiler? {/*should-i-try-out-the-compiler*/}
-Please note that the compiler is still in Beta and has many rough edges. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules).
+The compiler is now in RC and has been tested extensively in production. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules).
**You don't have to rush into using the compiler now. It's okay to wait until it reaches a stable release before adopting it.** However, we do appreciate trying it out in small experiments in your apps so that you can [provide feedback](#reporting-issues) to us to help make the compiler better.
@@ -124,43 +120,15 @@ Please note that the compiler is still in Beta and has many rough edges. While i
In addition to these docs, we recommend checking the [React Compiler Working Group](https://github.com/reactwg/react-compiler) for additional information and discussion about the compiler.
-### Installing eslint-plugin-react-compiler {/*installing-eslint-plugin-react-compiler*/}
+### Installing eslint-plugin-react-hooks {/*installing-eslint-plugin-react-compiler*/}
-React Compiler also powers an ESLint plugin. The ESLint plugin can be used **independently** of the compiler, meaning you can use the ESLint plugin even if you don't use the compiler.
+React Compiler also powers an ESLint plugin. You can try it out by installing eslint-plugin-react-hooks@^6.0.0-rc.1.
-npm install -D eslint-plugin-react-compiler@beta
+{`npm install -D eslint-plugin-react-hooks@^6.0.0-rc.1`}
-Then, add it to your ESLint config:
-
-```js
-import reactCompiler from 'eslint-plugin-react-compiler'
-
-export default [
- {
- plugins: {
- 'react-compiler': reactCompiler,
- },
- rules: {
- 'react-compiler/react-compiler': 'error',
- },
- },
-]
-```
-
-Or, in the deprecated eslintrc config format:
-
-```js
-module.exports = {
- plugins: [
- 'eslint-plugin-react-compiler',
- ],
- rules: {
- 'react-compiler/react-compiler': 'error',
- },
-}
-```
+See our [editor setup](/learn/editor-setup#linting) guide for more details.
The ESLint plugin will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase.
@@ -194,7 +162,7 @@ If you're starting a new project, you can enable the compiler on your entire cod
React Compiler works best with React 19 RC. If you are unable to upgrade, you can install the extra `react-compiler-runtime` package which will allow the compiled code to run on versions prior to 19. However, note that the minimum supported version is 17.
-npm install react-compiler-runtime@beta
+{`npm install react-compiler-runtime@rc`}
You should also add the correct `target` to your compiler config, where `target` is the major version of React you are targeting:
@@ -229,7 +197,7 @@ Similarly to apps, it is not necessary to fully compile 100% of your components
### Babel {/*usage-with-babel*/}
-npm install babel-plugin-react-compiler@beta
+{`npm install babel-plugin-react-compiler@rc`}
The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler.
@@ -284,7 +252,7 @@ Please refer to the [Next.js docs](https://nextjs.org/docs/app/api-reference/nex
Install `vite-plugin-babel`, and add the compiler's Babel plugin to it:
-npm install vite-plugin-babel
+{`npm install vite-plugin-babel`}
```js {2,14}
diff --git a/src/content/learn/referencing-values-with-refs.md b/src/content/learn/referencing-values-with-refs.md
index 4faf18786..fab6599f2 100644
--- a/src/content/learn/referencing-values-with-refs.md
+++ b/src/content/learn/referencing-values-with-refs.md
@@ -464,7 +464,7 @@ export default function Toggle() {
#### Fix debouncing {/*fix-debouncing*/}
-In this example, all button click handlers are ["debounced".](https://redd.one/blog/debounce-vs-throttle) To see what this means, press one of the buttons. Notice how the message appears a second later. If you press the button while waiting for the message, the timer will reset. So if you keep clicking the same button fast many times, the message won't appear until a second *after* you stop clicking. Debouncing lets you delay some action until the user "stops doing things".
+In this example, all button click handlers are ["debounced".](https://kettanaito.com/blog/debounce-vs-throttle) To see what this means, press one of the buttons. Notice how the message appears a second later. If you press the button while waiting for the message, the timer will reset. So if you keep clicking the same button fast many times, the message won't appear until a second *after* you stop clicking. Debouncing lets you delay some action until the user "stops doing things".
This example works, but not quite as intended. The buttons are not independent. To see the problem, click one of the buttons, and then immediately click another button. You'd expect that after a delay, you would see both button's messages. But only the last button's message shows up. The first button's message gets lost.
diff --git a/src/content/learn/removing-effect-dependencies.md b/src/content/learn/removing-effect-dependencies.md
index 9a871c6c3..9a848862a 100644
--- a/src/content/learn/removing-effect-dependencies.md
+++ b/src/content/learn/removing-effect-dependencies.md
@@ -1241,7 +1241,7 @@ export default function Timer() {
-Instead of reading `count` inside the Effect, you pass a `c => c + 1` instruction ("increment this number!") to React. React will apply it on the next render. And since you don't need to read the value of `count` inside your Effect anymore, so you can keep your Effect's dependencies empty (`[]`). This prevents your Effect from re-creating the interval on every tick.
+Instead of reading `count` inside the Effect, you pass a `c => c + 1` instruction ("increment this number!") to React. React will apply it on the next render. And since you don't need to read the value of `count` inside your Effect anymore, you can keep your Effect's dependencies empty (`[]`). This prevents your Effect from re-creating the interval on every tick.
diff --git a/src/content/learn/reusing-logic-with-custom-hooks.md b/src/content/learn/reusing-logic-with-custom-hooks.md
index ea8d0a313..b6562e2df 100644
--- a/src/content/learn/reusing-logic-with-custom-hooks.md
+++ b/src/content/learn/reusing-logic-with-custom-hooks.md
@@ -820,7 +820,7 @@ export default function ChatRoom({ roomId }) {
// ...
```
-and pass it as an input to another Hook:
+and passing it as an input to another Hook:
```js {6}
export default function ChatRoom({ roomId }) {
@@ -2081,7 +2081,6 @@ Write `useInterval` in the `useInterval.js` file and import it into the `useCoun
```js
-import { useState } from 'react';
import { useCounter } from './useCounter.js';
export default function Counter() {
diff --git a/src/content/learn/scaling-up-with-reducer-and-context.md b/src/content/learn/scaling-up-with-reducer-and-context.md
index c3da0c637..91fb6803f 100644
--- a/src/content/learn/scaling-up-with-reducer-and-context.md
+++ b/src/content/learn/scaling-up-with-reducer-and-context.md
@@ -461,11 +461,11 @@ export default function TaskApp() {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
// ...
return (
-
-
+
+
...
-
-
+
+
);
}
```
@@ -509,8 +509,8 @@ export default function TaskApp() {
}
return (
-
-
+
+
Day off in Kyoto
-
-
+
+
);
}
@@ -676,13 +676,13 @@ In the next step, you will remove prop passing.
Now you don't need to pass the list of tasks or the event handlers down the tree:
```js {4-5}
-
-
+
+
Day off in Kyoto
-
-
+
+
```
Instead, any component that needs the task list can read it from the `TaskContext`:
@@ -730,13 +730,13 @@ export default function TaskApp() {
);
return (
-
-
+
+
Day off in Kyoto
-
-
+
+
);
}
@@ -921,11 +921,11 @@ export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
return (
-
-
+
+
{children}
-
-
+
+
);
}
```
@@ -963,11 +963,11 @@ export function TasksProvider({ children }) {
);
return (
-
-
+
+
{children}
-
-
+
+
);
}
@@ -1174,11 +1174,11 @@ export function TasksProvider({ children }) {
);
return (
-
-
+
+
{children}
-
-
+
+
);
}
@@ -1363,4 +1363,3 @@ As your app grows, you may have many context-reducer pairs like this. This is a
- You can have many context-reducer pairs like this in your app.
-
diff --git a/src/content/learn/separating-events-from-effects.md b/src/content/learn/separating-events-from-effects.md
index 21276c287..03223183b 100644
--- a/src/content/learn/separating-events-from-effects.md
+++ b/src/content/learn/separating-events-from-effects.md
@@ -439,7 +439,7 @@ function ChatRoom({ roomId, theme }) {
// ...
```
-This solves the problem. Note that you had to *remove* `onConnected` from the list of your Effect's dependencies. **Effect Events are not reactive and must be omitted from dependencies.**
+This solves the problem. Note that you had to *remove* `theme` from the list of your Effect's dependencies, because it's no longer used in the Effect. You also don't need to *add* `onConnected` to it, because **Effect Events are not reactive and must be omitted from dependencies.**
Verify that the new behavior works as you would expect:
@@ -973,6 +973,23 @@ To fix this code, it's enough to follow the rules.
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
```js
import { useState, useEffect } from 'react';
@@ -1026,6 +1043,22 @@ If you remove the suppression comment, React will tell you that this Effect's co
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
```js
import { useState, useEffect } from 'react';
diff --git a/src/content/learn/typescript.md b/src/content/learn/typescript.md
index 7edf8eb6e..bf7483d1c 100644
--- a/src/content/learn/typescript.md
+++ b/src/content/learn/typescript.md
@@ -260,9 +260,9 @@ export default function MyApp() {
const [theme, setTheme] = useState('light');
return (
-
+
-
+
)
}
@@ -310,9 +310,9 @@ export default function MyApp() {
const object = useMemo(() => ({ kind: "complex" }), []);
return (
-
+
-
+
)
}
diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md
index 99190b03a..b74e2c38e 100644
--- a/src/content/reference/react-dom/client/hydrateRoot.md
+++ b/src/content/reference/react-dom/client/hydrateRoot.md
@@ -378,12 +378,13 @@ It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually
By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`:
-```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]]
+```js [[1, 7, "onCaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack", 15]]
import { hydrateRoot } from "react-dom/client";
+import App from "./App.js";
import { reportCaughtError } from "./reportError";
const container = document.getElementById("root");
-const root = hydrateRoot(container, {
+const root = hydrateRoot(container, , {
onCaughtError: (error, errorInfo) => {
if (error.message !== "Known error") {
reportCaughtError({
diff --git a/src/content/reference/react-dom/createPortal.md b/src/content/reference/react-dom/createPortal.md
index c04510f80..5717460df 100644
--- a/src/content/reference/react-dom/createPortal.md
+++ b/src/content/reference/react-dom/createPortal.md
@@ -240,7 +240,7 @@ export default function ModalContent({ onClose }) {
It's important to make sure that your app is accessible when using portals. For instance, you may need to manage keyboard focus so that the user can move the focus in and out of the portal in a natural way.
-Follow the [WAI-ARIA Modal Authoring Practices](https://www.w3.org/WAI/ARIA/apg/#dialog_modal) when creating modals. If you use a community package, ensure that it is accessible and follows these guidelines.
+Follow the [WAI-ARIA Modal Authoring Practices](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal) when creating modals. If you use a community package, ensure that it is accessible and follows these guidelines.
diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md
index 0ecd1972d..117fccac8 100644
--- a/src/content/reference/react-dom/preinit.md
+++ b/src/content/reference/react-dom/preinit.md
@@ -48,7 +48,7 @@ The `preinit` function provides the browser with a hint that it should start dow
* `options`: an object. It contains the following properties:
* `as`: a required string. The type of resource. Its possible values are `script` and `style`.
* `precedence`: a string. Required with stylesheets. Says where to insert the stylesheet relative to others. Stylesheets with higher precedence can override those with lower precedence. The possible values are `reset`, `low`, `medium`, `high`.
- * `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. It is required when `as` is set to `"fetch"`.
+ * `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`.
* `integrity`: a string. A cryptographic hash of the resource, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
* `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
* `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`.
diff --git a/src/content/reference/react-dom/static/prerender.md b/src/content/reference/react-dom/static/prerender.md
index f1ef38b44..4bbf6c35d 100644
--- a/src/content/reference/react-dom/static/prerender.md
+++ b/src/content/reference/react-dom/static/prerender.md
@@ -57,7 +57,7 @@ On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to
* **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
* **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-outside-the-shell) or [not.](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](/reference/react-dom/server/renderToReadableStream#logging-crashes-on-the-server) make sure that you still call `console.error`. You can also use it to [adjust the status code](/reference/react-dom/server/renderToReadableStream#setting-the-status-code) before the shell is emitted.
* **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
- * **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](/reference/react-dom/server/renderToReadableStream#aborting-server-rendering) and render the rest on the client.
+ * **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort prerendering](#aborting-prerendering) and render the rest on the client.
#### Returns {/*returns*/}
@@ -66,7 +66,9 @@ On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to
- `prelude`: a [Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) of HTML. You can use this stream to send a response in chunks, or you can read the entire stream into a string.
- If rendering fails, the Promise will be rejected. [Use this to output a fallback shell.](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-inside-the-shell)
+#### Caveats {/*caveats*/}
+`nonce` is not an available option when prerendering. Nonces must be unique per request and if you use nonces to secure your application with [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) it would be inappropriate and insecure to include the nonce value in the prerender itself.
@@ -229,7 +231,7 @@ async function renderToString() {
const {prelude} = await prerender( , {
bootstrapScripts: ['/main.js']
});
-
+
const reader = prelude.getReader();
let content = '';
while (true) {
@@ -287,11 +289,34 @@ Suspense-enabled data fetching without the use of an opinionated framework is no
---
+### Aborting prerendering {/*aborting-prerendering*/}
+
+You can force the prerender to "give up" after a timeout:
+
+```js {2-5,11}
+async function renderToString() {
+ const controller = new AbortController();
+ setTimeout(() => {
+ controller.abort()
+ }, 10000);
+
+ try {
+ // the prelude will contain all the HTML that was prerendered
+ // before the controller aborted.
+ const {prelude} = await prerender( , {
+ signal: controller.signal,
+ });
+ //...
+```
+
+Any Suspense boundaries with incomplete children will be included in the prelude in the fallback state.
+
+---
+
## Troubleshooting {/*troubleshooting*/}
### My stream doesn't start until the entire app is rendered {/*my-stream-doesnt-start-until-the-entire-app-is-rendered*/}
-The `prerender` response waits for the entire app to finish rendering, including waiting for all Suspense boundaries to resolve, before resolving. It is designed for static site generation (SSG) ahead of time and does not support streaming more content as it loads.
+The `prerender` response waits for the entire app to finish rendering, including waiting for all Suspense boundaries to resolve, before resolving. It is designed for static site generation (SSG) ahead of time and does not support streaming more content as it loads.
To stream content as it loads, use a streaming server render API like [renderToReadableStream](/reference/react-dom/server/renderToReadableStream).
-
\ No newline at end of file
diff --git a/src/content/reference/react-dom/static/prerenderToNodeStream.md b/src/content/reference/react-dom/static/prerenderToNodeStream.md
index b5bb60eaf..cc99c52d4 100644
--- a/src/content/reference/react-dom/static/prerenderToNodeStream.md
+++ b/src/content/reference/react-dom/static/prerenderToNodeStream.md
@@ -58,7 +58,7 @@ On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to
* **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
* **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](/reference/react-dom/server/renderToPipeableStream#recovering-from-errors-outside-the-shell) or [not.](/reference/react-dom/server/renderToPipeableStream#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](/reference/react-dom/server/renderToPipeableStream#logging-crashes-on-the-server) make sure that you still call `console.error`. You can also use it to [adjust the status code](/reference/react-dom/server/renderToPipeableStream#setting-the-status-code) before the shell is emitted.
* **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
- * **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](/reference/react-dom/server/renderToPipeableStream#aborting-server-rendering) and render the rest on the client.
+ * **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort prerendering](#aborting-prerendering) and render the rest on the client.
#### Returns {/*returns*/}
@@ -67,6 +67,10 @@ On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to
- `prelude`: a [Node.js Stream.](https://nodejs.org/api/stream.html) of HTML. You can use this stream to send a response in chunks, or you can read the entire stream into a string.
- If rendering fails, the Promise will be rejected. [Use this to output a fallback shell.](/reference/react-dom/server/renderToPipeableStream#recovering-from-errors-inside-the-shell)
+#### Caveats {/*caveats*/}
+
+`nonce` is not an available option when prerendering. Nonces must be unique per request and if you use nonces to secure your application with [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) it would be inappropriate and insecure to include the nonce value in the prerender itself.
+
### When should I use `prerenderToNodeStream`? {/*when-to-use-prerender*/}
@@ -91,7 +95,7 @@ app.use('/', async (request, response) => {
const { prelude } = await prerenderToNodeStream( , {
bootstrapScripts: ['/main.js'],
});
-
+
response.setHeader('Content-Type', 'text/plain');
prelude.pipe(response);
});
@@ -228,7 +232,7 @@ async function renderToString() {
const {prelude} = await prerenderToNodeStream( , {
bootstrapScripts: ['/main.js']
});
-
+
return new Promise((resolve, reject) => {
let data = '';
prelude.on('data', chunk => {
@@ -285,6 +289,30 @@ Suspense-enabled data fetching without the use of an opinionated framework is no
---
+### Aborting prerendering {/*aborting-prerendering*/}
+
+You can force the prerender to "give up" after a timeout:
+
+```js {2-5,11}
+async function renderToString() {
+ const controller = new AbortController();
+ setTimeout(() => {
+ controller.abort()
+ }, 10000);
+
+ try {
+ // the prelude will contain all the HTML that was prerendered
+ // before the controller aborted.
+ const {prelude} = await prerenderToNodeStream( , {
+ signal: controller.signal,
+ });
+ //...
+```
+
+Any Suspense boundaries with incomplete children will be included in the prelude in the fallback state.
+
+---
+
## Troubleshooting {/*troubleshooting*/}
### My stream doesn't start until the entire app is rendered {/*my-stream-doesnt-start-until-the-entire-app-is-rendered*/}
@@ -292,4 +320,3 @@ Suspense-enabled data fetching without the use of an opinionated framework is no
The `prerenderToNodeStream` response waits for the entire app to finish rendering, including waiting for all Suspense boundaries to resolve, before resolving. It is designed for static site generation (SSG) ahead of time and does not support streaming more content as it loads.
To stream content as it loads, use a streaming server render API like [renderToPipeableStream](/reference/react-dom/server/renderToPipeableStream).
-
diff --git a/src/content/reference/react/Activity.md b/src/content/reference/react/Activity.md
new file mode 100644
index 000000000..8b103938e
--- /dev/null
+++ b/src/content/reference/react/Activity.md
@@ -0,0 +1,1161 @@
+---
+title:
+version: experimental
+---
+
+
+
+**This API is experimental and is not available in a stable version of React yet.**
+
+You can try it by upgrading React packages to the most recent experimental version:
+
+- `react@experimental`
+- `react-dom@experimental`
+- `eslint-plugin-react-hooks@experimental`
+
+Experimental versions of React may contain bugs. Don't use them in production.
+
+
+
+
+
+`` lets you hide and show part of the UI.
+
+
+```js
+
+
+
+```
+
+
+
+
+
+---
+
+## Reference {/*reference*/}
+
+### `` {/*activity*/}
+
+Wrap a part of the UI in `` to manage its visibility state:
+
+```js
+import {unstable_Activity as Activity} from 'react';
+
+
+
+
+```
+
+When "hidden", the `children` of ` ` are not visible on the page. If a new `` mounts as "hidden" then it pre-renders the content at lower priority without blocking the visible content on the page, but it does not mount by creating Effects. When a "visible" Activity switches to "hidden" it conceptually unmounts by destroying all the Effects, but saves its state. This allows fast switching between "visible" and "hidden" states without recreating the state for a "hidden" Activity.
+
+In the future, "hidden" Activities may automatically destroy state based on resources like memory.
+
+#### Props {/*props*/}
+
+* `children`: The actual UI you intend to render.
+* **optional** `mode`: Either "visible" or "hidden". Defaults to "visible". When "hidden", updates to the children are deferred to lower priority. The component will not create Effects until the Activity is switched to "visible". If a "visible" Activity switches to "hidden", the Effects will be destroyed.
+
+#### Caveats {/*caveats*/}
+
+- While hidden, the `children` of `` are hidden on the page.
+- `` will unmount all Effects when switching from "visible" to "hidden" without destroying React or DOM state. This means Effects that are expected to run only once on mount will run again when switching from "hidden" to "visible". Conceptually, "hidden" Activities are unmounted, but they are not destroyed either. We recommend using [``](/reference/react/StrictMode) to catch any unexpected side-effects from this behavior.
+- When used with ``, hidden activities that reveal in a transition will activate an "enter" animation. Visible Activities hidden in a transition will activate an "exit" animation.
+- Parts of the UI wrapped in `` are not included in the SSR response.
+- Parts of the UI wrapped in `` will hydrate at a lower priority than other content.
+
+---
+
+## Usage {/*usage*/}
+
+### Pre-render part of the UI {/*pre-render-part-of-the-ui*/}
+
+You can pre-render part of the UI using ``:
+
+```js
+
+
+
+```
+
+When an Activity is rendered with `mode="hidden"`, the `children` are not visible on the page, but are rendered at lower priority than the visible content on the page.
+
+When the `mode` later switches to "visible", the pre-rendered children will mount and become visible. This can be used to prepare parts of the UI the user is likely to interact with next to reduce loading times.
+
+In the following example from [`useTransition`](/reference/react/useTransition#preventing-unwanted-loading-indicators), the `PostsTab` component fetches some data using `use`. When you click the “Posts” tab, the `PostsTab` component suspends, causing the button loading state to appear:
+
+
+
+```js
+import { Suspense, useState } from 'react';
+import TabButton from './TabButton.js';
+import AboutTab from './AboutTab.js';
+import PostsTab from './PostsTab.js';
+import ContactTab from './ContactTab.js';
+
+export default function TabContainer() {
+ const [tab, setTab] = useState('about');
+ return (
+ 🌀 Loading...}>
+ setTab('about')}
+ >
+ About
+
+ setTab('posts')}
+ >
+ Posts
+
+ setTab('contact')}
+ >
+ Contact
+
+
+ {tab === 'about' && }
+ {tab === 'posts' && }
+ {tab === 'contact' && }
+
+ );
+}
+```
+
+
+```js src/TabButton.js active
+import { useTransition } from 'react';
+
+export default function TabButton({ action, children, isActive }) {
+ const [isPending, startTransition] = useTransition();
+ if (isActive) {
+ return {children}
+ }
+ if (isPending) {
+ return {children} ;
+ }
+ return (
+ {
+ startTransition(() => {
+ action();
+ });
+ }}>
+ {children}
+
+ );
+}
+```
+
+```js src/AboutTab.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+
+export default function AboutTab() {
+ return (
+
+ Welcome to my profile!
+
+ );
+}
+```
+
+```js src/PostsTab.js hidden
+import {use, unstable_ViewTransition as ViewTransition} from 'react';
+import { fetchData } from './data.js';
+
+function PostsTab() {
+ const posts = use(fetchData('/posts'));
+ return (
+
+
+ {posts.map(post =>
+
+ )}
+
+
+ );
+}
+
+function Post({ title }) {
+ return (
+
+ {title}
+
+ );
+}
+
+export default PostsTab;
+```
+
+```js src/ContactTab.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+
+export default function ContactTab() {
+ return (
+
+
+ Send me a message!
+
+
+
+ You can find me online here:
+
+
+ admin@mysite.com
+ +123456789
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+// Note: the way you would do data fetching depends on
+// the framework that you use together with Suspense.
+// Normally, the caching logic would be inside a framework.
+
+let cache = new Map();
+
+export function fetchData(url) {
+ if (!cache.has(url)) {
+ cache.set(url, getData(url));
+ }
+ return cache.get(url);
+}
+
+async function getData(url) {
+ if (url.startsWith('/posts')) {
+ return await getPosts();
+ } else {
+ throw Error('Not implemented');
+ }
+}
+
+async function getPosts() {
+ // Add a fake delay to make waiting noticeable.
+ await new Promise(resolve => {
+ setTimeout(resolve, 1000);
+ });
+ let posts = [];
+ for (let i = 0; i < 10; i++) {
+ posts.push({
+ id: i,
+ title: 'Post #' + (i + 1)
+ });
+ }
+ return posts;
+}
+```
+
+```css
+body { height: 275px; }
+button { margin-right: 10px }
+b { display: inline-block; margin-right: 10px; }
+.pending { color: #777; }
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest",
+ "toastify-js": "1.12.0"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+In this example, the user needs to wait for the posts to load when clicking on the "Posts" tab.
+
+We can reduce the delay for the "Posts" tab by pre-rendering the inactive Tabs with a hidden ``:
+
+
+
+```js
+import { Suspense, useState, unstable_Activity as Activity } from "react";
+import TabButton from "./TabButton.js";
+import AboutTab from "./AboutTab.js";
+import PostsTab from "./PostsTab.js";
+import ContactTab from "./ContactTab.js";
+
+export default function TabContainer() {
+ const [tab, setTab] = useState("about");
+ return (
+ 🌀 Loading...}>
+ setTab("about")}>
+ About
+
+ setTab("posts")}>
+ Posts
+
+ setTab("contact")}>
+ Contact
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
+```
+
+
+```js src/TabButton.js active
+import { useTransition } from 'react';
+
+export default function TabButton({ action, children, isActive }) {
+ const [isPending, startTransition] = useTransition();
+ if (isActive) {
+ return {children}
+ }
+ if (isPending) {
+ return {children} ;
+ }
+ return (
+ {
+ startTransition(() => {
+ action();
+ });
+ }}>
+ {children}
+
+ );
+}
+```
+
+```js src/AboutTab.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+
+export default function AboutTab() {
+ return (
+
+ Welcome to my profile!
+
+ );
+}
+```
+
+```js src/PostsTab.js hidden
+import {use, unstable_ViewTransition as ViewTransition} from 'react';
+import { fetchData } from './data.js';
+
+function PostsTab() {
+ const posts = use(fetchData('/posts'));
+ return (
+
+
+ {posts.map(post =>
+
+ )}
+
+
+ );
+}
+
+function Post({ title }) {
+ return (
+
+ {title}
+
+ );
+}
+
+export default PostsTab;
+```
+
+```js src/ContactTab.js hidden
+import {unstable_ViewTransition as ViewTransition} from 'react';
+
+export default function ContactTab() {
+ return (
+
+
+ Send me a message!
+
+
+
+ You can find me online here:
+
+
+ admin@mysite.com
+ +123456789
+
+
+ );
+}
+```
+
+
+```js src/data.js hidden
+// Note: the way you would do data fetching depends on
+// the framework that you use together with Suspense.
+// Normally, the caching logic would be inside a framework.
+
+let cache = new Map();
+
+export function fetchData(url) {
+ if (!cache.has(url)) {
+ cache.set(url, getData(url));
+ }
+ return cache.get(url);
+}
+
+async function getData(url) {
+ if (url.startsWith('/posts')) {
+ return await getPosts();
+ } else {
+ throw Error('Not implemented');
+ }
+}
+
+async function getPosts() {
+ // Add a fake delay to make waiting noticeable.
+ await new Promise(resolve => {
+ setTimeout(resolve, 1000);
+ });
+ let posts = [];
+ for (let i = 0; i < 10; i++) {
+ posts.push({
+ id: i,
+ title: 'Post #' + (i + 1)
+ });
+ }
+ return posts;
+}
+```
+
+```css
+body { height: 275px; }
+button { margin-right: 10px }
+b { display: inline-block; margin-right: 10px; }
+.pending { color: #777; }
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest",
+ "toastify-js": "1.12.0"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+
+
+---
+
+### Keeping state for part of the UI {/*keeping-state-for-part-of-the-ui*/}
+
+
+You can keep state for parts of the UI by switching `` from "visible" to "hidden":
+
+```js
+
+
+
+```
+
+When an Activity switches from `mode="visible"` to "hidden", the `children` will become hidden on the page, and unmount by destroying all Effects, but will keep their React and DOM state.
+
+When the `mode` later switches to "visible", the saved state will be re-used when mounting the children by creating all the Effects. This can be used to keep state in parts of the UI the user is likely to interact with again to maintain DOM or React state.
+
+In the following example from [`useTransition`](/reference/react/useTransition#preventing-unwanted-loading-indicators), the `ContactTab` includes a `
+
+Enter/Exit:
+
+```
+ }>
+
+
+```
+
+In this scenario, these are two separate ViewTransition instances each with their own `view-transition-name`. This will be treated as an "exit" of the `` and an "enter" of the ``.
+
+You can achieve different effects depending on where you choose to place the `` boundary.
+
+---
+### Opting-out of an animation {/*opting-out-of-an-animation*/}
+
+Sometimes you're wrapping a large existing component, like a whole page, and you want to animate some updates, such as changing the theme. However, you don't want it to opt-in all updates inside the whole page to cross-fade when they're updating. Especially if you're incrementally adding more animations.
+
+You can use the class "none" to opt-out of an animation. By wrapping your children in a "none" you can disable animations for updates to them while the parent still triggers.
+
+```js
+
+
+
+ {children}
+
+
+
+```
+
+This will only animate if the theme changes and not if only the children update. The children can still opt-in again with their own `` but at least it's manual again.
+
+---
+
+### Customizing animations {/*customizing-animations*/}
+
+By default, `` includes the default cross-fade from the browser.
+
+To customize animations, you can provide props to the `` component to specify which animations to use, based on how the `` activates.
+
+For example, we can slow down the default cross fade animation:
+
+```js
+
+
+
+```
+
+And define slow-fade in CSS using view transition classes:
+
+```css
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+```
+
+
+
+```js src/Video.js hidden
+function Thumbnail({ video, children }) {
+ return (
+
+ );
+}
+
+export function Video({ video }) {
+ return (
+
+
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+ );
+}
+```
+
+```js
+import {
+ unstable_ViewTransition as ViewTransition,
+ useState,
+ startTransition
+} from 'react';
+import {Video} from "./Video";
+import videos from "./data"
+
+function Item() {
+ return (
+
+
+
+ );
+}
+
+export default function Component() {
+ const [showItem, setShowItem] = useState(false);
+ return (
+ <>
+ {
+ startTransition(() => {
+ setShowItem((prev) => !prev);
+ });
+ }}
+ >{showItem ? '➖' : '➕'}
+
+ {showItem ? : null}
+ >
+ );
+}
+```
+
+```js src/data.js hidden
+export default [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ }
+]
+```
+
+
+```css
+::view-transition-old(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+::view-transition-new(.slow-fade) {
+ animation-duration: 500ms;
+}
+
+#root {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ min-height: 200px;
+}
+button {
+ border: none;
+ border-radius: 50%;
+ width: 50px;
+ height: 50px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-color: #f0f8ff;
+ color: white;
+ font-size: 20px;
+ cursor: pointer;
+ transition: background-color 0.3s, border 0.3s;
+}
+button:hover {
+ border: 2px solid #ccc;
+ background-color: #e0e8ff;
+}
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+ margin-top: 1em;
+}
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+.video .info:hover {
+ text-decoration: underline;
+}
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ }
+}
+```
+
+
+
+In addition to setting the `default`, you can also provide configurations for `enter`, `exit`, `update`, and `share` animations.
+
+
+
+```js src/Video.js hidden
+function Thumbnail({ video, children }) {
+ return (
+
+ );
+}
+
+export function Video({ video }) {
+ return (
+
+
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+ );
+}
+```
+
+```js
+import {
+ unstable_ViewTransition as ViewTransition,
+ useState,
+ startTransition
+} from 'react';
+import {Video} from "./Video";
+import videos from "./data"
+
+function Item() {
+ return (
+
+
+
+ );
+}
+
+export default function Component() {
+ const [showItem, setShowItem] = useState(false);
+ return (
+ <>
+ {
+ startTransition(() => {
+ setShowItem((prev) => !prev);
+ });
+ }}
+ >{showItem ? '➖' : '➕'}
+
+ {showItem ? : null}
+ >
+ );
+}
+```
+
+```js src/data.js hidden
+export default [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ }
+]
+```
+
+
+```css
+::view-transition-old(.slide-in) {
+ animation-name: slideOutRight;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-new(.slide-in) {
+ animation-name: slideInRight;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-old(.slide-out) {
+ animation-name: slideOutLeft;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-new(.slide-out) {
+ animation-name: slideInLeft;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+@keyframes slideOutLeft {
+ from {
+ transform: translateX(0);
+ opacity: 1;
+ }
+ to {
+ transform: translateX(-100%);
+ opacity: 0;
+ }
+}
+
+@keyframes slideInLeft {
+ from {
+ transform: translateX(-100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+@keyframes slideOutRight {
+ from {
+ transform: translateX(0);
+ opacity: 1;
+ }
+ to {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+}
+
+@keyframes slideInRight {
+ from {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+@keyframes slideInRight {
+ from {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+#root {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ min-height: 200px;
+}
+button {
+ border: none;
+ border-radius: 50%;
+ width: 50px;
+ height: 50px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-color: #f0f8ff;
+ color: white;
+ font-size: 20px;
+ cursor: pointer;
+ transition: background-color 0.3s, border 0.3s;
+}
+button:hover {
+ border: 2px solid #ccc;
+ background-color: #e0e8ff;
+}
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+ margin-top: 1em;
+}
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+.video .info:hover {
+ text-decoration: underline;
+}
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ }
+}
+```
+
+
+
+### Customizing animations with types {/*customizing-animations-with-types*/}
+You can use the [`addTransitionType`](/reference/react/addTransitionType) API to add a class name to the child elements when a specific transition type is activated for a specific activation trigger. This allows you to customize the animation for each type of transition.
+
+For example, to customize the animation for all forward and backward navigations:
+
+```js
+
+ ...
+
+
+// in your router:
+startTransition(() => {
+ addTransitionType('navigation-' + navigationType);
+});
+```
+
+When the ViewTransition activates a "navigation-back" animation, React will add the class name "slide-right". When the ViewTransition activates a "navigation-forward" animation, React will add the class name "slide-left".
+
+In the future, routers and other libraries may add support for standard view-transition types and styles.
+
+
+
+```js src/Video.js hidden
+function Thumbnail({ video, children }) {
+ return (
+
+ );
+}
+
+export function Video({ video }) {
+ return (
+
+
+
+
+
{video.title}
+
{video.description}
+
+
+
+ );
+}
+```
+
+```js
+import {
+ unstable_ViewTransition as ViewTransition,
+ unstable_addTransitionType as addTransitionType,
+ useState,
+ startTransition,
+} from "react";
+import {Video} from "./Video";
+import videos from "./data"
+
+function Item() {
+ return (
+
+
+
+ );
+}
+
+export default function Component() {
+ const [showItem, setShowItem] = useState(false);
+ return (
+ <>
+
+ {
+ startTransition(() => {
+ if (showItem) {
+ addTransitionType("remove-video-back")
+ } else {
+ addTransitionType("add-video-back")
+ }
+ setShowItem((prev) => !prev);
+ });
+ }}
+ >⬅️
+ {
+ startTransition(() => {
+ if (showItem) {
+ addTransitionType("remove-video-forward")
+ } else {
+ addTransitionType("add-video-forward")
+ }
+ setShowItem((prev) => !prev);
+ });
+ }}
+ >➡️
+
+ {showItem ? : null}
+ >
+ );
+}
+```
+
+```js src/data.js hidden
+export default [
+ {
+ id: '1',
+ title: 'First video',
+ description: 'Video description',
+ image: 'blue',
+ }
+]
+```
+
+
+```css
+::view-transition-old(.slide-in-back) {
+ animation-name: slideOutRight;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-new(.slide-in-back) {
+ animation-name: slideInRight;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-old(.slide-out-back) {
+ animation-name: slideOutLeft;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-new(.slide-out-back) {
+ animation-name: slideInLeft;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-old(.slide-in-forward) {
+ animation-name: slideOutLeft;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-new(.slide-in-forward) {
+ animation-name: slideInLeft;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-old(.slide-out-forward) {
+ animation-name: slideOutRight;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+::view-transition-new(.slide-out-forward) {
+ animation-name: slideInRight;
+ animation-duration: 500ms;
+ animation-timing-function: ease-in-out;
+}
+
+@keyframes slideOutLeft {
+ from {
+ transform: translateX(0);
+ opacity: 1;
+ }
+ to {
+ transform: translateX(-100%);
+ opacity: 0;
+ }
+}
+
+@keyframes slideInLeft {
+ from {
+ transform: translateX(-100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+@keyframes slideOutRight {
+ from {
+ transform: translateX(0);
+ opacity: 1;
+ }
+ to {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+}
+
+@keyframes slideInRight {
+ from {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+@keyframes slideInRight {
+ from {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+#root {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ min-height: 200px;
+}
+button {
+ border: none;
+ border-radius: 50%;
+ width: 50px;
+ height: 50px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-color: #f0f8ff;
+ color: white;
+ font-size: 20px;
+ cursor: pointer;
+ transition: background-color 0.3s, border 0.3s;
+}
+button:hover {
+ border: 2px solid #ccc;
+ background-color: #e0e8ff;
+}
+.button-container {
+ display: flex;
+}
+.thumbnail {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ display: flex;
+ overflow: hidden;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ border-radius: 0.5rem;
+ outline-offset: 2px;
+ width: 8rem;
+ vertical-align: middle;
+ background-color: #ffffff;
+ background-size: cover;
+ user-select: none;
+}
+.thumbnail.blue {
+ background-image: conic-gradient(at top right, #c76a15, #087ea4, #2b3491);
+}
+.video {
+ display: flex;
+ flex-direction: row;
+ gap: 0.75rem;
+ align-items: center;
+ margin-top: 1em;
+}
+.video .link {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ gap: 0.125rem;
+ outline-offset: 4px;
+ cursor: pointer;
+}
+.video .info {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ margin-left: 8px;
+ gap: 0.125rem;
+}
+.video .info:hover {
+ text-decoration: underline;
+}
+.video-title {
+ font-size: 15px;
+ line-height: 1.25;
+ font-weight: 700;
+ color: #23272f;
+}
+.video-description {
+ color: #5e687e;
+ font-size: 13px;
+}
+```
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "experimental",
+ "react-dom": "experimental",
+ "react-scripts": "latest"
+ }
+}
+```
+
+
+
+### Building View Transition enabled routers {/*building-view-transition-enabled-routers*/}
+
+React waits for any pending Navigation to finish to ensure that scroll restoration happens within the animation. If the Navigation is blocked on React, your router must unblock in `useLayoutEffect` since `useEffect` would lead to a deadlock.
+
+If a `startTransition` is started from the legacy popstate event, such as during a "back"-navigation then it must finish synchronously to ensure scroll and form restoration works correctly. This is in conflict with running a View Transition animation. Therefore, React will skip animations from popstate. Therefore animations won't run for the back button. You can fix this by upgrading your router to use the Navigation API.
+
+---
+
+## Troubleshooting {/*troubleshooting*/}
+
+### My `` is not activating {/*my-viewtransition-is-not-activating*/}
+
+`` only activates if it is placed is before any DOM node:
+
+```js [3, 5]
+function Component() {
+ return (
+
+ Hi
+
+ );
+}
+```
+
+To fix, ensure that the `` comes before any other DOM nodes:
+
+```js [3, 5]
+function Component() {
+ return (
+
+ Hi
+
+ );
+}
+```
+
+### I'm getting an error "There are two `` components with the same name mounted at the same time." {/*two-viewtransition-with-same-name*/}
+
+This error occurs when two `` components with the same `name` are mounted at the same time:
+
+
+```js [3]
+function Item() {
+ // 🚩 All items will get the same "name".
+ return ... ;
+}
+
+function ItemList({items}) {
+ return (
+ <>
+ {item.map(item => )}
+ >
+ );
+}
+```
+
+This will cause the View Transition to error. In development, React detects this issue to surface it and logs two errors:
+
+
+
+
+There are two `` components with the same name mounted at the same time. This is not supported and will cause View Transitions to error. Try to use a more unique name e.g. by using a namespace prefix and adding the id of an item to the name.
+{' '}at Item
+{' '}at ItemList
+
+
+
+
+
+The existing `` duplicate has this stack trace.
+{' '}at Item
+{' '}at ItemList
+
+
+
+
+To fix, ensure that there's only one `` with the same name mounted at a time in the entire app by ensuring the `name` is unique, or adding an `id` to the name:
+
+```js [3]
+function Item({id}) {
+ // ✅ All items will get the same "name".
+ return ... ;
+}
+
+function ItemList({items}) {
+ return (
+ <>
+ {item.map(item => )}
+ >
+ );
+}
+```
diff --git a/src/content/reference/react/addTransitionType.md b/src/content/reference/react/addTransitionType.md
new file mode 100644
index 000000000..f292ea755
--- /dev/null
+++ b/src/content/reference/react/addTransitionType.md
@@ -0,0 +1,182 @@
+---
+title: unstable_addTransitionType
+version: experimental
+---
+
+
+
+**This API is experimental and is not available in a stable version of React yet.**
+
+You can try it by upgrading React packages to the most recent experimental version:
+
+- `react@experimental`
+- `react-dom@experimental`
+- `eslint-plugin-react-hooks@experimental`
+
+Experimental versions of React may contain bugs. Don't use them in production.
+
+
+
+
+
+`unstable_addTransitionType` lets you specify the cause of a transition.
+
+
+```js
+startTransition(() => {
+ unstable_addTransitionType('my-transition-type');
+ setState(newState);
+});
+```
+
+
+
+
+
+---
+
+## Reference {/*reference*/}
+
+### `addTransitionType` {/*addtransitiontype*/}
+
+#### Parameters {/*parameters*/}
+
+- `type`: The type of transition to add. This can be any string.
+
+#### Returns {/*returns*/}
+
+`startTransition` does not return anything.
+
+#### Caveats {/*caveats*/}
+
+- If multiple transitions are combined, all Transition Types are collected. You can also add more than one type to a Transition.
+- Transition Types are reset after each commit. This means a `` fallback will associate the types after a `startTransition`, but revealing the content does not.
+
+---
+
+## Usage {/*usage*/}
+
+### Adding the cause of a transition {/*adding-the-cause-of-a-transition*/}
+
+Call `addTransitionType` inside of `startTransition` to indicate the cause of a transition:
+
+``` [[1, 6, "unstable_addTransitionType"], [2, 5, "startTransition", [3, 6, "'submit-click'"]]
+import { startTransition, unstable_addTransitionType } from 'react';
+
+function Submit({action) {
+ function handleClick() {
+ startTransition(() => {
+ unstable_addTransitionType('submit-click');
+ action();
+ });
+ }
+
+ return Click me ;
+}
+
+```
+
+When you call addTransitionType inside the scope of startTransition , React will associate submit-click as one of the causes for the Transition.
+
+Currently, Transition Types can be used to customize different animations based on what caused the Transition. You have three different ways to choose from for how to use them:
+
+- [Customize animations using browser view transition types](#customize-animations-using-browser-view-transition-types)
+- [Customize animations using `View Transition` Class](#customize-animations-using-view-transition-class)
+- [Customize animations using `ViewTransition` events](#customize-animations-using-viewtransition-events)
+
+In the future, we plan to support more use cases for using the cause of a transition.
+
+---
+### Customize animations using browser view transition types {/*customize-animations-using-browser-view-transition-types*/}
+
+When a [`ViewTransition`](/reference/react/ViewTransition) activates from a transition, React adds all the Transition Types as browser [view transition types](https://www.w3.org/TR/css-view-transitions-2/#active-view-transition-pseudo-examples) to the element.
+
+This allows you to customize different animations based on CSS scopes:
+
+```js [11]
+function Component() {
+ return (
+
+ Hello
+
+ );
+}
+
+startTransition(() => {
+ unstable_addTransitionType('my-transition-type');
+ setShow(true);
+});
+```
+
+```css
+:root:active-view-transition-type(my-transition-type) {
+ &::view-transition-...(...) {
+ ...
+ }
+}
+```
+
+---
+
+### Customize animations using `View Transition` Class {/*customize-animations-using-view-transition-class*/}
+
+You can customize animations for an activated `ViewTransition` based on type by passing an object to the View Transition Class:
+
+```js
+function Component() {
+ return (
+
+ Hello
+
+ );
+}
+
+// ...
+startTransition(() => {
+ unstable_addTransitionType('my-transition-type');
+ setState(newState);
+});
+```
+
+If multiple types match, then they're joined together. If no types match then the special "default" entry is used instead. If any type has the value "none" then that wins and the ViewTransition is disabled (not assigned a name).
+
+These can be combined with enter/exit/update/layout/share props to match based on kind of trigger and Transition Type.
+
+```js
+
+```
+
+---
+
+### Customize animations using `ViewTransition` events {/*customize-animations-using-viewtransition-events*/}
+
+You can imperatively customize animations for an activated `ViewTransition` based on type using View Transition events:
+
+```
+ {
+ if (types.includes('navigation-back')) {
+ ...
+ } else if (types.includes('navigation-forward')) {
+ ...
+ } else {
+ ...
+ }
+}}>
+```
+
+This allows you to pick different imperative Animations based on the cause.
+
+---
+
+## Troubleshooting {/*troubleshooting*/}
+
+### TODO {/*todo2*/}
diff --git a/src/content/reference/react/apis.md b/src/content/reference/react/apis.md
index cbab4a0e6..6cb990908 100644
--- a/src/content/reference/react/apis.md
+++ b/src/content/reference/react/apis.md
@@ -11,7 +11,6 @@ In addition to [Hooks](/reference/react) and [Components](/reference/react/compo
---
* [`createContext`](/reference/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](/reference/react/useContext)
-* [`forwardRef`](/reference/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](/reference/react/useRef)
* [`lazy`](/reference/react/lazy) lets you defer loading a component's code until it's rendered for the first time.
* [`memo`](/reference/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](/reference/react/useMemo) and [`useCallback`.](/reference/react/useCallback)
* [`startTransition`](/reference/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](/reference/react/useTransition)
diff --git a/src/content/reference/react/cloneElement.md b/src/content/reference/react/cloneElement.md
index 6bcea51b0..4e29ff203 100644
--- a/src/content/reference/react/cloneElement.md
+++ b/src/content/reference/react/cloneElement.md
@@ -414,9 +414,9 @@ export default function List({ items, renderItem }) {
{items.map((item, index) => {
const isHighlighted = index === selectedIndex;
return (
-
+
{renderItem(item)}
-
+
);
})}
```
@@ -472,12 +472,12 @@ export default function List({ items, renderItem }) {
{items.map((item, index) => {
const isHighlighted = index === selectedIndex;
return (
-
{renderItem(item)}
-
+
);
})}
diff --git a/src/content/reference/react/createContext.md b/src/content/reference/react/createContext.md
index 03b09f8af..2161fa63c 100644
--- a/src/content/reference/react/createContext.md
+++ b/src/content/reference/react/createContext.md
@@ -38,14 +38,15 @@ const ThemeContext = createContext('light');
`createContext` returns a context object.
-**The context object itself does not hold any information.** It represents _which_ context other components read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/reference/react/useContext) in components below to read it. The context object has a few properties:
+**The context object itself does not hold any information.** It represents _which_ context other components read or provide. Typically, you will use [`SomeContext`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/reference/react/useContext) in components below to read it. The context object has a few properties:
-* `SomeContext.Provider` lets you provide the context value to components.
+* `SomeContext` lets you provide the context value to components.
* `SomeContext.Consumer` is an alternative and rarely used way to read the context value.
+* `SomeContext.Provider` is a legacy way to provide the context value before React 19.
---
-### `SomeContext.Provider` {/*provider*/}
+### `SomeContext` Provider {/*provider*/}
Wrap your components into a context provider to specify the value of this context for all components inside:
@@ -54,13 +55,21 @@ function App() {
const [theme, setTheme] = useState('light');
// ...
return (
-
+
-
+
);
}
```
+
+
+Starting in React 19, you can render `` as a provider.
+
+In older versions of React, use ``.
+
+
+
#### Props {/*provider-props*/}
* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
@@ -141,11 +150,11 @@ function App() {
// ...
return (
-
-
+
+
-
-
+
+
);
}
```
@@ -187,11 +196,11 @@ import { ThemeContext, AuthContext } from './Contexts.js';
function App() {
// ...
return (
-
-
+
+
-
-
+
+
);
}
```
@@ -214,4 +223,3 @@ const ThemeContext = createContext('light');
This value never changes. React only uses this value as a fallback if it can't find a matching provider above.
To make context change over time, [add state and wrap components in a context provider.](/reference/react/useContext#updating-data-passed-via-context)
-
diff --git a/src/content/reference/react/experimental_taintObjectReference.md b/src/content/reference/react/experimental_taintObjectReference.md
index b5b9e513d..c7b565e9b 100644
--- a/src/content/reference/react/experimental_taintObjectReference.md
+++ b/src/content/reference/react/experimental_taintObjectReference.md
@@ -1,8 +1,9 @@
---
title: experimental_taintObjectReference
+version: experimental
---
-
+
**This API is experimental and is not available in a stable version of React yet.**
@@ -16,7 +17,7 @@ Experimental versions of React may contain bugs. Don't use them in production.
This API is only available inside React Server Components.
-
+
diff --git a/src/content/reference/react/experimental_taintUniqueValue.md b/src/content/reference/react/experimental_taintUniqueValue.md
index de9a9beda..ea92ff6be 100644
--- a/src/content/reference/react/experimental_taintUniqueValue.md
+++ b/src/content/reference/react/experimental_taintUniqueValue.md
@@ -1,8 +1,9 @@
---
title: experimental_taintUniqueValue
+version: experimental
---
-
+
**This API is experimental and is not available in a stable version of React yet.**
@@ -16,7 +17,7 @@ Experimental versions of React may contain bugs. Don't use them in production.
This API is only available inside [React Server Components](/reference/rsc/use-client).
-
+
diff --git a/src/content/reference/react/experimental_useEffectEvent.md b/src/content/reference/react/experimental_useEffectEvent.md
index e819f041c..954cf6587 100644
--- a/src/content/reference/react/experimental_useEffectEvent.md
+++ b/src/content/reference/react/experimental_useEffectEvent.md
@@ -1,8 +1,9 @@
---
title: experimental_useEffectEvent
+version: experimental
---
-
+
**This API is experimental and is not available in a stable version of React yet.**
@@ -14,7 +15,7 @@ You can try it by upgrading React packages to the most recent experimental versi
Experimental versions of React may contain bugs. Don't use them in production.
-
+
diff --git a/src/content/reference/react/legacy.md b/src/content/reference/react/legacy.md
index b22a9c97e..f4e3ebe28 100644
--- a/src/content/reference/react/legacy.md
+++ b/src/content/reference/react/legacy.md
@@ -30,6 +30,6 @@ These APIs were removed in React 19:
* [`createFactory`](https://18.react.dev/reference/react/createFactory): use JSX instead.
* Class Components: [`static contextTypes`](https://18.react.dev//reference/react/Component#static-contexttypes): use [`static contextType`](#static-contexttype) instead.
* Class Components: [`static childContextTypes`](https://18.react.dev//reference/react/Component#static-childcontexttypes): use [`static contextType`](#static-contexttype) instead.
-* Class Components: [`static getChildContext`](https://18.react.dev//reference/react/Component#getchildcontext): use [`Context.Provider`](/reference/react/createContext#provider) instead.
+* Class Components: [`static getChildContext`](https://18.react.dev//reference/react/Component#getchildcontext): use [`Context`](/reference/react/createContext#provider) instead.
* Class Components: [`static propTypes`](https://18.react.dev//reference/react/Component#static-proptypes): use a type system like [TypeScript](https://www.typescriptlang.org/) instead.
* Class Components: [`this.refs`](https://18.react.dev//reference/react/Component#refs): use [`createRef`](/reference/react/createRef) instead.
diff --git a/src/content/reference/react/memo.md b/src/content/reference/react/memo.md
index 26fa9ed9c..01d6290f1 100644
--- a/src/content/reference/react/memo.md
+++ b/src/content/reference/react/memo.md
@@ -226,12 +226,12 @@ export default function MyApp() {
}
return (
-
+
Switch theme
-
+
);
}
diff --git a/src/content/reference/react/use.md b/src/content/reference/react/use.md
index 557a71cad..91e19c4b4 100644
--- a/src/content/reference/react/use.md
+++ b/src/content/reference/react/use.md
@@ -74,9 +74,9 @@ To pass context to a `Button`, wrap it or one of its parent components into the
```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]]
function MyPage() {
return (
-
+
-
+
);
}
@@ -116,9 +116,9 @@ const ThemeContext = createContext(null);
export default function MyApp() {
return (
-
+
-
+
)
}
diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md
index ce06e7035..f69c49af9 100644
--- a/src/content/reference/react/useContext.md
+++ b/src/content/reference/react/useContext.md
@@ -38,11 +38,11 @@ function MyComponent() {
#### Returns {/*returns*/}
-`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/reference/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.
+`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/reference/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.
#### Caveats {/*caveats*/}
-* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `` **needs to be *above*** the component doing the `useContext()` call.
+* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `` **needs to be *above*** the component doing the `useContext()` call.
* React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/reference/react/memo) does not prevent the children receiving fresh context values.
* If your build system produces duplicates modules in the output (which can happen with symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison.
@@ -70,9 +70,9 @@ To pass context to a `Button`, wrap it or one of its parent components into the
```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]]
function MyPage() {
return (
-
+
-
+
);
}
@@ -98,9 +98,9 @@ const ThemeContext = createContext(null);
export default function MyApp() {
return (
-
+
-
+
)
}
@@ -183,14 +183,14 @@ Often, you'll want the context to change over time. To update context, combine i
function MyPage() {
const [theme, setTheme] = useState('dark');
return (
-
+
{
setTheme('light');
}}>
Switch to light theme
-
+
);
}
```
@@ -213,7 +213,7 @@ const ThemeContext = createContext(null);
export default function MyApp() {
const [theme, setTheme] = useState('light');
return (
-
+
Use dark mode
-
+
)
}
@@ -317,14 +317,14 @@ const CurrentUserContext = createContext(null);
export default function MyApp() {
const [currentUser, setCurrentUser] = useState(null);
return (
-
-
+
);
}
@@ -411,8 +411,8 @@ export default function MyApp() {
const [theme, setTheme] = useState('light');
const [currentUser, setCurrentUser] = useState(null);
return (
-
-
+
Use dark mode
-
-
+
+
)
}
@@ -596,16 +596,16 @@ export default function MyApp() {
function MyProviders({ children, theme, setTheme }) {
const [currentUser, setCurrentUser] = useState(null);
return (
-
-
+
{children}
-
-
+
+
);
}
@@ -775,11 +775,11 @@ export function TasksProvider({ children }) {
);
return (
-
-
+
+
{children}
-
-
+
+
);
}
@@ -978,9 +978,9 @@ export default function MyApp() {
const [theme, setTheme] = useState('light');
return (
<>
-
+
-
+
{
setTheme(theme === 'dark' ? 'light' : 'dark');
}}>
@@ -1067,13 +1067,13 @@ function Button({ children, onClick }) {
You can override the context for a part of the tree by wrapping that part in a provider with a different value.
```js {3,5}
-
+
...
-
+
-
+
...
-
+
```
You can nest and override providers as many times as you need.
@@ -1093,9 +1093,9 @@ const ThemeContext = createContext(null);
export default function MyApp() {
return (
-
+
-
+
)
}
@@ -1104,9 +1104,9 @@ function Form() {
Sign up
Log in
-
+
-
+
);
}
@@ -1230,9 +1230,9 @@ export default function Section({ children }) {
const level = useContext(LevelContext);
return (
);
}
@@ -1302,9 +1302,9 @@ function MyApp() {
}
return (
-
+
-
+
);
}
```
@@ -1330,9 +1330,9 @@ function MyApp() {
}), [currentUser, login]);
return (
-
+
-
+
);
}
```
@@ -1349,8 +1349,8 @@ Read more about [`useMemo`](/reference/react/useMemo#skipping-re-rendering-of-co
There are a few common ways that this can happen:
-1. You're rendering `` in the same component (or below) as where you're calling `useContext()`. Move `` *above and outside* the component calling `useContext()`.
-2. You may have forgotten to wrap your component with ``, or you might have put it in a different part of the tree than you thought. Check whether the hierarchy is right using [React DevTools.](/learn/react-developer-tools)
+1. You're rendering `` in the same component (or below) as where you're calling `useContext()`. Move `` *above and outside* the component calling `useContext()`.
+2. You may have forgotten to wrap your component with ``, or you might have put it in a different part of the tree than you thought. Check whether the hierarchy is right using [React DevTools.](/learn/react-developer-tools)
3. You might be running into some build issue with your tooling that causes `SomeContext` as seen from the providing component and `SomeContext` as seen by the reading component to be two different objects. This can happen if you use symlinks, for example. You can verify this by assigning them to globals like `window.SomeContext1` and `window.SomeContext2` and then checking whether `window.SomeContext1 === window.SomeContext2` in the console. If they're not the same, fix that issue on the build tool level.
### I am always getting `undefined` from my context although the default value is different {/*i-am-always-getting-undefined-from-my-context-although-the-default-value-is-different*/}
@@ -1359,9 +1359,9 @@ You might have a provider without a `value` in the tree:
```js {1,2}
// 🚩 Doesn't work: no value prop
-
+
-
+
```
If you forget to specify `value`, it's like passing `value={undefined}`.
@@ -1370,18 +1370,18 @@ You may have also mistakingly used a different prop name by mistake:
```js {1,2}
// 🚩 Doesn't work: prop should be called "value"
-
+
-
+
```
In both of these cases you should see a warning from React in the console. To fix them, call the prop `value`:
```js {1,2}
// ✅ Passing the value prop
-
+
-
+
```
-Note that the [default value from your `createContext(defaultValue)` call](#specifying-a-fallback-default-value) is only used **if there is no matching provider above at all.** If there is a `` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the context value.
+Note that the [default value from your `createContext(defaultValue)` call](#specifying-a-fallback-default-value) is only used **if there is no matching provider above at all.** If there is a `` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the context value.
diff --git a/src/content/reference/react/useOptimistic.md b/src/content/reference/react/useOptimistic.md
index d191bbb55..b69a532f0 100644
--- a/src/content/reference/react/useOptimistic.md
+++ b/src/content/reference/react/useOptimistic.md
@@ -66,39 +66,42 @@ For example, when a user types a message into the form and hits the "Send" butto
```js src/App.js
-import { useOptimistic, useState, useRef } from "react";
+import { useOptimistic, useState, useRef, startTransition } from "react";
import { deliverMessage } from "./actions.js";
-function Thread({ messages, sendMessage }) {
+function Thread({ messages, sendMessageAction }) {
const formRef = useRef();
- async function formAction(formData) {
+ function formAction(formData) {
addOptimisticMessage(formData.get("message"));
formRef.current.reset();
- await sendMessage(formData);
+ startTransition(async () => {
+ await sendMessageAction(formData);
+ });
}
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [
- ...state,
{
text: newMessage,
sending: true
- }
+ },
+ ...state,
]
);
return (
<>
+
+
+ Send
+
{optimisticMessages.map((message, index) => (
{message.text}
{!!message.sending && (Sending...) }
))}
-
-
- Send
-
+
>
);
}
@@ -107,11 +110,13 @@ export default function App() {
const [messages, setMessages] = useState([
{ text: "Hello there!", sending: false, key: 1 }
]);
- async function sendMessage(formData) {
+ async function sendMessageAction(formData) {
const sentMessage = await deliverMessage(formData.get("message"));
- setMessages((messages) => [...messages, { text: sentMessage }]);
+ startTransition(() => {
+ setMessages((messages) => [{ text: sentMessage }, ...messages]);
+ })
}
- return ;
+ return ;
}
```
diff --git a/src/content/reference/react/useTransition.md b/src/content/reference/react/useTransition.md
index 6b7c511e7..73a754df7 100644
--- a/src/content/reference/react/useTransition.md
+++ b/src/content/reference/react/useTransition.md
@@ -77,8 +77,8 @@ function SubmitButton({ submitAction }) {
{
- startTransition(() => {
- submitAction();
+ startTransition(async () => {
+ await submitAction();
});
}}
>
@@ -163,7 +163,7 @@ function CheckoutForm() {
The function passed to `startTransition` is called the "Action". You can update state and (optionally) perform side effects within an Action, and the work will be done in the background without blocking user interactions on the page. A Transition can include multiple Actions, and while a Transition is in progress, your UI stays responsive. For example, if the user clicks a tab but then changes their mind and clicks another tab, the second click will be immediately handled without waiting for the first update to finish.
-To give the user feedback about in-progress Transitions, to `isPending` state switches to `true` at the first call to `startTransition`, and stays `true` until all Actions complete and the final state is shown to the user. Transitions ensure side effects in Actions to complete in order to [prevent unwanted loading indicators](#preventing-unwanted-loading-indicators), and you can provide immediate feedback while the Transition is in progress with `useOptimistic`.
+To give the user feedback about in-progress Transitions, the `isPending` state switches to `true` at the first call to `startTransition`, and stays `true` until all Actions complete and the final state is shown to the user. Transitions ensure side effects in Actions to complete in order to [prevent unwanted loading indicators](#preventing-unwanted-loading-indicators), and you can provide immediate feedback while the Transition is in progress with `useOptimistic`.
@@ -227,9 +227,9 @@ import { startTransition } from "react";
export default function Item({action}) {
function handleChange(event) {
- // To expose an action prop, call the callback in startTransition.
+ // To expose an action prop, await the callback in startTransition.
startTransition(async () => {
- action(event.target.value);
+ await action(event.target.value);
})
}
return (
@@ -585,10 +585,9 @@ This solution makes the app feel slow, because the user must wait each time they
You can expose an `action` prop from a component to allow a parent to call an Action.
-
For example, this `TabButton` component wraps its `onClick` logic in an `action` prop:
-```js {8-10}
+```js {8-12}
export default function TabButton({ action, children, isActive }) {
const [isPending, startTransition] = useTransition();
if (isActive) {
@@ -596,8 +595,10 @@ export default function TabButton({ action, children, isActive }) {
}
return (
{
- startTransition(() => {
- action();
+ startTransition(async () => {
+ // await the action that's passed in.
+ // This allows it to be either sync or async.
+ await action();
});
}}>
{children}
@@ -656,10 +657,15 @@ export default function TabButton({ action, children, isActive }) {
if (isActive) {
return {children}
}
+ if (isPending) {
+ return {children} ;
+ }
return (
- {
- startTransition(() => {
- action();
+ {
+ startTransition(async () => {
+ // await the action that's passed in.
+ // This allows it to be either sync or async.
+ await action();
});
}}>
{children}
@@ -729,10 +735,19 @@ export default function ContactTab() {
```css
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
+.pending { color: #777; }
```
+
+
+When exposing an `action` prop from a component, you should `await` it inside the transition.
+
+This allows the `action` callback to be either synchronous or asynchronous without requiring an additional `startTransition` to wrap the `await` in the action.
+
+
+
---
### Displaying a pending visual state {/*displaying-a-pending-visual-state*/}
@@ -804,8 +819,8 @@ export default function TabButton({ action, children, isActive }) {
}
return (
{
- startTransition(() => {
- action();
+ startTransition(async () => {
+ await action();
});
}}>
{children}
@@ -1095,8 +1110,8 @@ export default function TabButton({ action, children, isActive }) {
}
return (
{
- startTransition(() => {
- action();
+ startTransition(async () => {
+ await action();
});
}}>
{children}
@@ -1822,8 +1837,8 @@ import {startTransition} from 'react';
export default function Item({action}) {
function handleChange(e) {
// Update the quantity in an Action.
- startTransition(() => {
- action(e.target.value);
+ startTransition(async () => {
+ await action(e.target.value);
});
}
return (
@@ -1933,3 +1948,162 @@ When clicking multiple times, it's possible for previous requests to finish afte
This is expected, because Actions within a Transition do not guarantee execution order. For common use cases, React provides higher-level abstractions like [`useActionState`](/reference/react/useActionState) and [`` actions](/reference/react-dom/components/form) that handle ordering for you. For advanced use cases, you'll need to implement your own queuing and abort logic to handle this.
+Example of `useActionState` handling execution order:
+
+
+
+```json package.json hidden
+{
+ "dependencies": {
+ "react": "beta",
+ "react-dom": "beta"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ }
+}
+```
+
+```js src/App.js
+import { useState, useActionState } from "react";
+import { updateQuantity } from "./api";
+import Item from "./Item";
+import Total from "./Total";
+
+export default function App({}) {
+ // Store the actual quantity in separate state to show the mismatch.
+ const [clientQuantity, setClientQuantity] = useState(1);
+ const [quantity, updateQuantityAction, isPending] = useActionState(
+ async (prevState, payload) => {
+ setClientQuantity(payload);
+ const savedQuantity = await updateQuantity(payload);
+ return savedQuantity; // Return the new quantity to update the state
+ },
+ 1 // Initial quantity
+ );
+
+ return (
+
+
Checkout
+ -
+
+
+
+ );
+}
+
+```
+
+```js src/Item.js
+import {startTransition} from 'react';
+
+export default function Item({action}) {
+ function handleChange(e) {
+ // Update the quantity in an Action.
+ startTransition(() => {
+ action(e.target.value);
+ });
+ }
+ return (
+
+ Eras Tour Tickets
+ Quantity:
+
+
+ )
+}
+```
+
+```js src/Total.js
+const intl = new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD"
+});
+
+export default function Total({ clientQuantity, savedQuantity, isPending }) {
+ return (
+
+
Total:
+
+
+ {isPending
+ ? "🌀 Updating..."
+ : `${intl.format(savedQuantity * 9999)}`}
+
+
+ {!isPending &&
+ clientQuantity !== savedQuantity &&
+ `Wrong total, expected: ${intl.format(clientQuantity * 9999)}`}
+
+
+
+ );
+}
+```
+
+```js src/api.js
+let firstRequest = true;
+export async function updateQuantity(newName) {
+ return new Promise((resolve, reject) => {
+ if (firstRequest === true) {
+ firstRequest = false;
+ setTimeout(() => {
+ firstRequest = true;
+ resolve(newName);
+ // Simulate every other request being slower
+ }, 1000);
+ } else {
+ setTimeout(() => {
+ resolve(newName);
+ }, 50);
+ }
+ });
+}
+```
+
+```css
+.item {
+ display: flex;
+ align-items: center;
+ justify-content: start;
+}
+
+.item label {
+ flex: 1;
+ text-align: right;
+}
+
+.item input {
+ margin-left: 4px;
+ width: 60px;
+ padding: 4px;
+}
+
+.total {
+ height: 50px;
+ line-height: 25px;
+ display: flex;
+ align-content: center;
+ justify-content: space-between;
+}
+
+.total div {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+}
+
+.error {
+ color: red;
+}
+```
+
+
diff --git a/src/content/reference/rsc/directives.md b/src/content/reference/rsc/directives.md
index 42256de49..c17bcf3a8 100644
--- a/src/content/reference/rsc/directives.md
+++ b/src/content/reference/rsc/directives.md
@@ -4,7 +4,7 @@ title: Directives
-Directives are for use in [React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
+Directives are for use in [React Server Components](/reference/rsc/server-components).
diff --git a/src/content/reference/rsc/server-functions.md b/src/content/reference/rsc/server-functions.md
index d29693894..2603c1099 100644
--- a/src/content/reference/rsc/server-functions.md
+++ b/src/content/reference/rsc/server-functions.md
@@ -4,7 +4,7 @@ title: Server Functions
-Server Functions are for use in [React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
+Server Functions are for use in [React Server Components](/reference/rsc/server-components).
**Note:** Until September 2024, we referred to all Server Functions as "Server Actions". If a Server Function is passed to an action prop or called from inside an action then it is a Server Action, but not all Server Functions are Server Actions. The naming in this documentation has been updated to reflect that Server Functions can be used for multiple purposes.
@@ -28,7 +28,7 @@ To support Server Functions as a bundler or framework, we recommend pinning to a
-When a Server Functions is defined with the [`"use server"`](/reference/rsc/use-server) directive, your framework will automatically create a reference to the server function, and pass that reference to the Client Component. When that function is called on the client, React will send a request to the server to execute the function, and return the result.
+When a Server Function is defined with the [`"use server"`](/reference/rsc/use-server) directive, your framework will automatically create a reference to the Server Function, and pass that reference to the Client Component. When that function is called on the client, React will send a request to the server to execute the function, and return the result.
Server Functions can be created in Server Components and passed as props to Client Components, or they can be imported and used in Client Components.
@@ -54,7 +54,7 @@ function EmptyNote () {
}
```
-When React renders the `EmptyNote` Server Function, it will create a reference to the `createNoteAction` function, and pass that reference to the `Button` Client Component. When the button is clicked, React will send a request to the server to execute the `createNoteAction` function with the reference provided:
+When React renders the `EmptyNote` Server Component, it will create a reference to the `createNoteAction` function, and pass that reference to the `Button` Client Component. When the button is clicked, React will send a request to the server to execute the `createNoteAction` function with the reference provided:
```js {5}
"use client";
diff --git a/src/content/reference/rsc/use-client.md b/src/content/reference/rsc/use-client.md
index fe6f5b1ed..e259585c4 100644
--- a/src/content/reference/rsc/use-client.md
+++ b/src/content/reference/rsc/use-client.md
@@ -5,7 +5,7 @@ titleForTitleTag: "'use client' directive"
-`'use client'` is for use with [React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
+`'use client'` is for use with [React Server Components](/reference/rsc/server-components).
diff --git a/src/content/reference/rsc/use-server.md b/src/content/reference/rsc/use-server.md
index 4d6fb4639..58b1f0ee1 100644
--- a/src/content/reference/rsc/use-server.md
+++ b/src/content/reference/rsc/use-server.md
@@ -5,7 +5,7 @@ titleForTitleTag: "'use server' directive"
-`'use server'` is for use with [using React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
+`'use server'` is for use with [using React Server Components](/reference/rsc/server-components).
diff --git a/src/content/reference/rules/components-and-hooks-must-be-pure.md b/src/content/reference/rules/components-and-hooks-must-be-pure.md
index d3d54560e..6da6d49bb 100644
--- a/src/content/reference/rules/components-and-hooks-must-be-pure.md
+++ b/src/content/reference/rules/components-and-hooks-must-be-pure.md
@@ -207,7 +207,7 @@ A component's props and state are immutable [snapshots](learn/state-as-a-snapsho
You can think of the props and state values as snapshots that are updated after rendering. For this reason, you don't modify the props or state variables directly: instead you pass new props, or use the setter function provided to you to tell React that state needs to update the next time the component is rendered.
### Don't mutate Props {/*props*/}
-Props are immutable because if you mutate them, the application will produce inconsistent output, which can be hard to debug since it may or may not work depending on the circumstance.
+Props are immutable because if you mutate them, the application will produce inconsistent output, which can be hard to debug as it may or may not work depending on the circumstances.
```js {2}
function Post({ item }) {
@@ -307,7 +307,7 @@ function useIconStyle(icon) {
}
```
-If you were to mutate the Hooks arguments, the custom hook's memoization will become incorrect, so it's important to avoid doing that.
+If you were to mutate the Hook's arguments, the custom hook's memoization will become incorrect, so it's important to avoid doing that.
```js {4}
style = useIconStyle(icon); // `style` is memoized based on `icon`
@@ -327,7 +327,7 @@ Similarly, it's important to not modify the return values of Hooks, as they may
## Values are immutable after being passed to JSX {/*values-are-immutable-after-being-passed-to-jsx*/}
-Don't mutate values after they've been used in JSX. Move the mutation before the JSX is created.
+Don't mutate values after they've been used in JSX. Move the mutation to before the JSX is created.
When you use JSX in an expression, React may eagerly evaluate the JSX before the component finishes rendering. This means that mutating values after they've been passed to JSX can lead to outdated UIs, as React won't know to update the component's output.
diff --git a/src/content/versions.md b/src/content/versions.md
index 8530f6324..54bc309f1 100644
--- a/src/content/versions.md
+++ b/src/content/versions.md
@@ -11,7 +11,7 @@ The React docs at [react.dev](https://react.dev) provide documentation for the l
We aim to keep the docs updated within major versions, and do not publish versions for each minor or patch version. When a new major is released, we archive the docs for the previous version as `x.react.dev`. See our [versioning policy](/community/versioning-policy) for more info.
You can find an archive of previous major versions below.
-## Latest version: 19.0 {/*latest-version*/}
+## Latest version: 19.1 {/*latest-version*/}
- [react.dev](https://react.dev) {/*docs-19*/}
@@ -51,6 +51,7 @@ For versions older than React 15, see [15.react.dev](https://15.react.dev).
- [React 19 Deep Dive: Coordinating HTML](https://www.youtube.com/watch?v=IBBN-s77YSI)
**Releases**
+- [v19.1.0 (March, 2025)](https://github.com/facebook/react/blob/main/CHANGELOG.md#1910-march-28-2025)
- [v19.0.0 (December, 2024)](https://github.com/facebook/react/blob/main/CHANGELOG.md#1900-december-5-2024)
### React 18 {/*react-18*/}
diff --git a/src/content/warnings/react-dom-test-utils.md b/src/content/warnings/react-dom-test-utils.md
index 2dc33e5b2..794bb1d11 100644
--- a/src/content/warnings/react-dom-test-utils.md
+++ b/src/content/warnings/react-dom-test-utils.md
@@ -2,8 +2,6 @@
title: react-dom/test-utils Deprecation Warnings
---
-TODO: update for 19?
-
## ReactDOMTestUtils.act() warning {/*reactdomtestutilsact-warning*/}
`act` from `react-dom/test-utils` has been deprecated in favor of `act` from `react`.
diff --git a/src/content/warnings/react-test-renderer.md b/src/content/warnings/react-test-renderer.md
index da7623fe2..dca1761b4 100644
--- a/src/content/warnings/react-test-renderer.md
+++ b/src/content/warnings/react-test-renderer.md
@@ -2,8 +2,6 @@
title: react-test-renderer Deprecation Warnings
---
-TODO: Update this for 19?
-
## ReactTestRenderer.create() warning {/*reacttestrenderercreate-warning*/}
react-test-renderer is deprecated. A warning will fire whenever calling ReactTestRenderer.create() or ReactShallowRender.render(). The react-test-renderer package will remain available on NPM but will not be maintained and may break with new React features or changes to React's internals.
diff --git a/src/pages/errors/[errorCode].tsx b/src/pages/errors/[errorCode].tsx
index a67c5742d..c8cf28ad8 100644
--- a/src/pages/errors/[errorCode].tsx
+++ b/src/pages/errors/[errorCode].tsx
@@ -26,7 +26,7 @@ export default function ErrorDecoderPage({
);
return (
-
+
*/}
-
+
);
}
diff --git a/src/sidebarBlog.json b/src/sidebarBlog.json
index 5562a5a6c..6e92e849c 100644
--- a/src/sidebarBlog.json
+++ b/src/sidebarBlog.json
@@ -11,6 +11,27 @@
"path": "/blog",
"skipBreadcrumb": true,
"routes": [
+ {
+ "title": "React Labs: View Transitions, Activity, and more",
+ "titleForHomepage": "View Transitions and Activity",
+ "icon": "blog",
+ "date": "April 23, 2025",
+ "path": "/blog/2025/04/23/react-labs-view-transitions-activity-and-more"
+ },
+ {
+ "title": "React Compiler RC",
+ "titleForHomepage": "React Compiler RC",
+ "icon": "blog",
+ "date": "April 21, 2025",
+ "path": "/blog/2025/04/21/react-compiler-rc"
+ },
+ {
+ "title": "Sunsetting Create React App",
+ "titleForHomepage": "Sunsetting Create React App",
+ "icon": "blog",
+ "date": "February 14, 2025",
+ "path": "/blog/2025/02/14/sunsetting-create-react-app"
+ },
{
"title": "React 19",
"titleForHomepage": "React 19",
diff --git a/src/sidebarReference.json b/src/sidebarReference.json
index 851b544d0..5e3939842 100644
--- a/src/sidebarReference.json
+++ b/src/sidebarReference.json
@@ -103,6 +103,16 @@
{
"title": "",
"path": "/reference/react/Suspense"
+ },
+ {
+ "title": "",
+ "path": "/reference/react/Activity",
+ "version": "experimental"
+ },
+ {
+ "title": "",
+ "path": "/reference/react/ViewTransition",
+ "version": "experimental"
}
]
},
@@ -144,12 +154,17 @@
{
"title": "experimental_taintObjectReference",
"path": "/reference/react/experimental_taintObjectReference",
- "version": "canary"
+ "version": "experimental"
},
{
"title": "experimental_taintUniqueValue",
"path": "/reference/react/experimental_taintUniqueValue",
- "version": "canary"
+ "version": "experimental"
+ },
+ {
+ "title": "unstable_addTransitionType",
+ "path": "/reference/react/addTransitionType",
+ "version": "experimental"
}
]
},
diff --git a/src/styles/index.css b/src/styles/index.css
index 281111092..6b2915be4 100644
--- a/src/styles/index.css
+++ b/src/styles/index.css
@@ -12,7 +12,17 @@
font-style: normal;
font-weight: 400;
font-display: swap;
- src: url('/fonts/Source-Code-Pro-Regular.woff2') format('woff2');
+ src: url('https://react.dev/fonts/Source-Code-Pro-Regular.woff2')
+ format('woff2');
+ }
+
+ @font-face {
+ font-family: 'Source Code Pro';
+ font-style: normal;
+ font-weight: 700;
+ font-display: swap;
+ src: url('https://react.dev/fonts/Source-Code-Pro-Bold.woff2')
+ format('woff2');
}
/* Latin */