diff --git a/.eslintrc b/.eslintrc index f617dea26..f8b03f98a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,11 +2,13 @@ "root": true, "extends": "next/core-web-vitals", "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint"], + "plugins": ["@typescript-eslint", "eslint-plugin-react-compiler"], "rules": { "no-unused-vars": "off", - "@typescript-eslint/no-unused-vars": ["error", { "varsIgnorePattern": "^_" }], - "react-hooks/exhaustive-deps": "error" + "@typescript-eslint/no-unused-vars": ["error", {"varsIgnorePattern": "^_"}], + "react-hooks/exhaustive-deps": "error", + "react/no-unknown-property": ["error", {"ignore": ["meta"]}], + "react-compiler/react-compiler": "error" }, "env": { "node": true, diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index 87dcfdc73..83e7f2e8a 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -7,22 +7,32 @@ on: - main # change this if your default branch is named differently workflow_dispatch: +permissions: {} + jobs: analyze: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up node - uses: actions/setup-node@v1 + uses: actions/setup-node@v4 with: node-version: '20.x' + cache: yarn + cache-dependency-path: yarn.lock + + - name: Restore cached node_modules + uses: actions/cache@v4 + with: + path: '**/node_modules' + key: node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - - name: Install dependencies - uses: bahmutov/npm-install@v1.7.10 + - name: Install deps + run: yarn install --frozen-lockfile - name: Restore next build - uses: actions/cache@v2 + uses: actions/cache@v4 id: restore-build-cache env: cache-name: cache-next-build @@ -41,13 +51,13 @@ jobs: run: npx -p nextjs-bundle-analysis@0.5.0 report - name: Upload bundle - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: path: .next/analyze/__bundle_analysis.json name: bundle_analysis.json - name: Download base branch bundle stats - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@268677152d06ba59fcec7a7f0b5d961b6ccd7e1e if: success() && github.event.number with: workflow: analyze.yml @@ -73,7 +83,7 @@ jobs: run: ls -laR .next/analyze/base && npx -p nextjs-bundle-analysis compare - name: Upload analysis comment - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: analysis_comment.txt path: .next/analyze/__bundle_analysis_comment.txt @@ -82,7 +92,7 @@ jobs: run: echo ${{ github.event.number }} > ./pr_number - name: Upload PR number - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: pr_number path: ./pr_number diff --git a/.github/workflows/analyze_comment.yml b/.github/workflows/analyze_comment.yml index 5a3047cfc..1e086b9b7 100644 --- a/.github/workflows/analyze_comment.yml +++ b/.github/workflows/analyze_comment.yml @@ -2,10 +2,12 @@ name: Analyze Bundle (Comment) on: workflow_run: - workflows: ["Analyze Bundle"] + workflows: ['Analyze Bundle'] types: - completed +permissions: {} + jobs: comment: runs-on: ubuntu-latest @@ -14,7 +16,7 @@ jobs: github.event.workflow_run.conclusion == 'success' }} steps: - name: Download base branch bundle stats - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@268677152d06ba59fcec7a7f0b5d961b6ccd7e1e with: workflow: analyze.yml run_id: ${{ github.event.workflow_run.id }} @@ -22,7 +24,7 @@ jobs: path: analysis_comment.txt - name: Download PR number - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@268677152d06ba59fcec7a7f0b5d961b6ccd7e1e with: workflow: analyze.yml run_id: ${{ github.event.workflow_run.id }} @@ -48,7 +50,7 @@ jobs: echo "pr-number=$pr_number" >> $GITHUB_OUTPUT - name: Comment - uses: marocchino/sticky-pull-request-comment@v2 + uses: marocchino/sticky-pull-request-comment@52423e01640425a022ef5fd42c6fb5f633a02728 with: header: next-bundle-analysis number: ${{ steps.get-comment-body.outputs.pr-number }} diff --git a/.github/workflows/discord_notify.yml b/.github/workflows/discord_notify.yml new file mode 100644 index 000000000..2f5b2a497 --- /dev/null +++ b/.github/workflows/discord_notify.yml @@ -0,0 +1,32 @@ +name: Discord Notify + +on: + pull_request_target: + types: [opened, ready_for_review] + +permissions: {} + +jobs: + check_maintainer: + uses: facebook/react/.github/workflows/shared_check_maintainer.yml@main + permissions: + # Used by check_maintainer + contents: read + with: + actor: ${{ github.event.pull_request.user.login }} + + notify: + if: ${{ needs.check_maintainer.outputs.is_core_team == 'true' }} + needs: check_maintainer + runs-on: ubuntu-latest + steps: + - name: Discord Webhook Action + uses: tsickert/discord-webhook@v6.0.0 + with: + webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }} + embed-author-name: ${{ github.event.pull_request.user.login }} + embed-author-url: ${{ github.event.pull_request.user.html_url }} + embed-author-icon-url: ${{ github.event.pull_request.user.avatar_url }} + embed-title: '#${{ github.event.number }} (+${{github.event.pull_request.additions}} -${{github.event.pull_request.deletions}}): ${{ github.event.pull_request.title }}' + embed-description: ${{ github.event.pull_request.body }} + embed-url: ${{ github.event.pull_request.html_url }} diff --git a/.github/workflows/label_core_team_prs.yml b/.github/workflows/label_core_team_prs.yml new file mode 100644 index 000000000..f9b3328ee --- /dev/null +++ b/.github/workflows/label_core_team_prs.yml @@ -0,0 +1,41 @@ +name: Label Core Team PRs + +on: + pull_request_target: + +permissions: {} + +env: + TZ: /usr/share/zoneinfo/America/Los_Angeles + # https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cache-segment-restore-timeout + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 1 + +jobs: + check_maintainer: + uses: facebook/react/.github/workflows/shared_check_maintainer.yml@main + permissions: + # Used by check_maintainer + contents: read + with: + actor: ${{ github.event.pull_request.user.login }} + + label: + if: ${{ needs.check_maintainer.outputs.is_core_team == 'true' }} + runs-on: ubuntu-latest + needs: check_maintainer + permissions: + # Used to add labels on issues + issues: write + # Used to add labels on PRs + pull-requests: write + steps: + - name: Label PR as React Core Team + uses: actions/github-script@v7 + with: + script: | + github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: ${{ github.event.number }}, + labels: ['React Core Team'] + }); diff --git a/.github/workflows/site_lint.yml b/.github/workflows/site_lint.yml index 34ca6d7b8..81a04601c 100644 --- a/.github/workflows/site_lint.yml +++ b/.github/workflows/site_lint.yml @@ -7,6 +7,8 @@ on: pull_request: types: [opened, synchronize, reopened] +permissions: {} + jobs: lint: runs-on: ubuntu-latest @@ -14,14 +16,22 @@ jobs: name: Lint on node 20.x and ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: Use Node.js 20.x - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: 20.x + cache: yarn + cache-dependency-path: yarn.lock + + - name: Restore cached node_modules + uses: actions/cache@v4 + with: + path: '**/node_modules' + key: node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - - name: Install deps and build (with cache) - uses: bahmutov/npm-install@v1.8.32 + - name: Install deps + run: yarn install --frozen-lockfile - name: Lint codebase run: yarn ci-check diff --git a/README.md b/README.md index 958865c19..069a467e5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This repo contains the source code and documentation powering [si.react.dev](htt ### Prerequisites 1. Git -1. Node: any 12.x version starting with v12.0.0 or greater +1. Node: any version starting with v16.8.0 or greater 1. Yarn: See [Yarn website for installation instructions](https://yarnpkg.com/lang/en/docs/install/) 1. A fork of the repo (for any contributions) 1. A clone of the [si.react.dev repo](https://github.com/reactjs/si.react.dev) on your local machine diff --git a/next-env.d.ts b/next-env.d.ts index 4f11a03dc..52e831b43 100644 --- a/next-env.d.ts +++ b/next-env.d.ts @@ -2,4 +2,4 @@ /// // NOTE: This file should not be edited -// see https://nextjs.org/docs/basic-features/typescript for more information. +// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. diff --git a/next.config.js b/next.config.js index 61ff1944a..861792c8e 100644 --- a/next.config.js +++ b/next.config.js @@ -9,10 +9,8 @@ const nextConfig = { pageExtensions: ['jsx', 'js', 'ts', 'tsx', 'mdx', 'md'], reactStrictMode: true, experimental: { - // TODO: Remove after https://github.com/vercel/next.js/issues/49355 is fixed - appDir: false, scrollRestoration: true, - legacyBrowsers: false, + reactCompiler: true, }, env: {}, webpack: (config, {dev, isServer, ...options}) => { diff --git a/package.json b/package.json index 26bb39657..6d6b53f92 100644 --- a/package.json +++ b/package.json @@ -18,26 +18,27 @@ "ci-check": "npm-run-all prettier:diff --parallel lint tsc lint-heading-ids rss", "tsc": "tsc --noEmit", "start": "next start", - "postinstall": "patch-package && (is-ci || husky install .husky)", + "postinstall": "is-ci || husky install .husky", "check-all": "npm-run-all prettier lint:fix tsc rss", "rss": "node scripts/generateRss.js" }, "dependencies": { "@codesandbox/sandpack-react": "2.13.5", - "@docsearch/css": "3.0.0-alpha.41", - "@docsearch/react": "3.0.0-alpha.41", + "@docsearch/css": "^3.8.3", + "@docsearch/react": "^3.8.3", "@headlessui/react": "^1.7.0", + "@radix-ui/react-context-menu": "^2.1.5", "body-scroll-lock": "^3.1.3", "classnames": "^2.2.6", "date-fns": "^2.16.1", "debounce": "^1.2.1", "github-slugger": "^1.3.0", - "next": "^13.4.1", + "next": "15.1.0", "next-remote-watch": "^1.0.0", "parse-numeric-range": "^1.2.0", - "react": "^0.0.0-experimental-16d053d59-20230506", + "react": "^19.0.0", "react-collapsed": "4.0.4", - "react-dom": "^0.0.0-experimental-16d053d59-20230506", + "react-dom": "^19.0.0", "remark-frontmatter": "^4.0.1", "remark-gfm": "^3.0.1" }, @@ -53,13 +54,14 @@ "@types/mdx-js__react": "^1.5.2", "@types/node": "^14.6.4", "@types/parse-numeric-range": "^0.0.1", - "@types/react": "^18.0.9", - "@types/react-dom": "^18.0.5", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", "@typescript-eslint/eslint-plugin": "^5.36.2", "@typescript-eslint/parser": "^5.36.2", "asyncro": "^3.0.0", "autoprefixer": "^10.4.2", "babel-eslint": "10.x", + "babel-plugin-react-compiler": "19.0.0-beta-e552027-20250112", "eslint": "7.x", "eslint-config-next": "12.0.3", "eslint-config-react-app": "^5.2.1", @@ -67,6 +69,7 @@ "eslint-plugin-import": "2.x", "eslint-plugin-jsx-a11y": "6.x", "eslint-plugin-react": "7.x", + "eslint-plugin-react-compiler": "^19.0.0-beta-e552027-20250112", "eslint-plugin-react-hooks": "^0.0.0-experimental-fabef7a6b-20221215", "fs-extra": "^9.0.1", "globby": "^11.0.1", @@ -77,7 +80,6 @@ "mdast-util-to-string": "^1.1.0", "metro-cache": "0.72.2", "npm-run-all": "^4.1.5", - "patch-package": "^6.2.2", "postcss": "^8.4.5", "postcss-flexbugs-fixes": "4.2.1", "postcss-preset-env": "^6.7.0", @@ -93,7 +95,7 @@ "retext-smartypants": "^4.0.0", "rss": "^1.2.2", "tailwindcss": "^3.4.1", - "typescript": "^4.0.2", + "typescript": "^5.7.2", "unist-util-visit": "^2.0.3", "webpack-bundle-analyzer": "^4.5.0" }, @@ -108,5 +110,6 @@ "lint-staged": { "*.{js,ts,jsx,tsx,css}": "yarn prettier", "src/**/*.md": "yarn fix-headings" - } + }, + "packageManager": "yarn@1.22.22" } diff --git a/patches/next+13.4.1.patch b/patches/next+13.4.1.patch deleted file mode 100644 index 6de490aa4..000000000 --- a/patches/next+13.4.1.patch +++ /dev/null @@ -1,22 +0,0 @@ -diff --git a/node_modules/next/dist/server/render.js b/node_modules/next/dist/server/render.js -index a1f8648..1b3d608 100644 ---- a/node_modules/next/dist/server/render.js -+++ b/node_modules/next/dist/server/render.js -@@ -758,9 +758,14 @@ async function renderToHTML(req, res, pathname, query, renderOpts) { - // Always using react concurrent rendering mode with required react version 18.x - const renderShell = async (EnhancedApp, EnhancedComponent)=>{ - const content = renderContent(EnhancedApp, EnhancedComponent); -- return await (0, _nodewebstreamshelper.renderToInitialStream)({ -- ReactDOMServer: _serverbrowser.default, -- element: content -+ return new Promise((resolve, reject) => { -+ (0, _nodewebstreamshelper.renderToInitialStream)({ -+ ReactDOMServer: _serverbrowser.default, -+ element: content, -+ streamOptions: { -+ onError: reject -+ } -+ }).then(resolve, reject); - }); - }; - const createBodyResult = (0, _tracer.getTracer)().wrap(_constants2.RenderSpan.createBodyResult, (initialStream, suffix)=>{ diff --git a/patches/next-remote-watch+1.0.0.patch b/patches/next-remote-watch+1.0.0.patch deleted file mode 100644 index c9ecef84d..000000000 --- a/patches/next-remote-watch+1.0.0.patch +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/node_modules/next-remote-watch/bin/next-remote-watch b/node_modules/next-remote-watch/bin/next-remote-watch -index c055b66..a2f749c 100755 ---- a/node_modules/next-remote-watch/bin/next-remote-watch -+++ b/node_modules/next-remote-watch/bin/next-remote-watch -@@ -66,7 +66,10 @@ app.prepare().then(() => { - } - } - -- app.server.hotReloader.send('reloadPage') -+ app.server.hotReloader.send({ -+ event: 'serverOnlyChanges', -+ pages: ['/[[...markdownPath]]'] -+ }); - } - ) - } diff --git a/postcss.config.js b/postcss.config.js index 427294522..d55c43c90 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -17,4 +17,4 @@ module.exports = { }, }, }, -} +}; diff --git a/public/.well-known/atproto-did b/public/.well-known/atproto-did new file mode 100644 index 000000000..ad8b0a36b --- /dev/null +++ b/public/.well-known/atproto-did @@ -0,0 +1 @@ +did:plc:uorpbnp2q32vuvyeruwauyhe \ No newline at end of file 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/public/images/brand/logo_dark.svg b/public/images/brand/logo_dark.svg new file mode 100644 index 000000000..265777fa3 --- /dev/null +++ b/public/images/brand/logo_dark.svg @@ -0,0 +1,12 @@ + + + React-Logo-Filled (1) + + + + + + + + + \ No newline at end of file diff --git a/public/images/brand/logo_light.svg b/public/images/brand/logo_light.svg new file mode 100644 index 000000000..bbe5a8994 --- /dev/null +++ b/public/images/brand/logo_light.svg @@ -0,0 +1,10 @@ + + + React-Logo-Filled (1) + + + + + + + \ No newline at end of file diff --git a/public/images/brand/wordmark_dark.svg b/public/images/brand/wordmark_dark.svg new file mode 100644 index 000000000..ec028ae21 --- /dev/null +++ b/public/images/brand/wordmark_dark.svg @@ -0,0 +1,15 @@ + + + Group + + + + + + + + + + + + \ No newline at end of file diff --git a/public/images/brand/wordmark_light.svg b/public/images/brand/wordmark_light.svg new file mode 100644 index 000000000..2de8f3cc7 --- /dev/null +++ b/public/images/brand/wordmark_light.svg @@ -0,0 +1,11 @@ + + + Group + + + + + + + + \ No newline at end of file diff --git a/public/images/docs/diagrams/prerender.dark.png b/public/images/docs/diagrams/prerender.dark.png new file mode 100644 index 000000000..1e7d67e13 Binary files /dev/null and b/public/images/docs/diagrams/prerender.dark.png differ diff --git a/public/images/docs/diagrams/prerender.png b/public/images/docs/diagrams/prerender.png new file mode 100644 index 000000000..ababa5493 Binary files /dev/null and b/public/images/docs/diagrams/prerender.png differ diff --git a/public/images/docs/diagrams/prewarm.dark.png b/public/images/docs/diagrams/prewarm.dark.png new file mode 100644 index 000000000..461406039 Binary files /dev/null and b/public/images/docs/diagrams/prewarm.dark.png differ diff --git a/public/images/docs/diagrams/prewarm.png b/public/images/docs/diagrams/prewarm.png new file mode 100644 index 000000000..f6ec1c49d Binary files /dev/null and b/public/images/docs/diagrams/prewarm.png differ diff --git a/public/images/team/andrey-lunyov.jpg b/public/images/team/andrey-lunyov.jpg deleted file mode 100644 index aeaaec06a..000000000 Binary files a/public/images/team/andrey-lunyov.jpg and /dev/null differ diff --git a/public/images/team/hendrik.jpg b/public/images/team/hendrik.jpg new file mode 100644 index 000000000..b39ea5be2 Binary files /dev/null and b/public/images/team/hendrik.jpg differ diff --git a/public/images/team/jordan.jpg b/public/images/team/jordan.jpg new file mode 100644 index 000000000..d8874a29f Binary files /dev/null and b/public/images/team/jordan.jpg differ diff --git a/public/images/team/kathryn-middleton.jpg b/public/images/team/kathryn-middleton.jpg deleted file mode 100644 index 904c3b134..000000000 Binary files a/public/images/team/kathryn-middleton.jpg and /dev/null differ diff --git a/public/images/team/lauren.jpg b/public/images/team/lauren.jpg index cb08b9725..a8615aa00 100644 Binary files a/public/images/team/lauren.jpg and b/public/images/team/lauren.jpg differ diff --git a/public/images/team/luna-wei.jpg b/public/images/team/luna-wei.jpg deleted file mode 100644 index cdc4a2b6a..000000000 Binary files a/public/images/team/luna-wei.jpg and /dev/null differ diff --git a/public/images/team/mike.jpg b/public/images/team/mike.jpg new file mode 100644 index 000000000..39fe23fea Binary files /dev/null and b/public/images/team/mike.jpg differ diff --git a/public/images/team/noahlemen.jpg b/public/images/team/noahlemen.jpg deleted file mode 100644 index e3f788d89..000000000 Binary files a/public/images/team/noahlemen.jpg and /dev/null differ diff --git a/public/images/team/pieter.jpg b/public/images/team/pieter.jpg new file mode 100644 index 000000000..d098e5abe Binary files /dev/null and b/public/images/team/pieter.jpg differ diff --git a/public/images/team/sam.jpg b/public/images/team/sam.jpg deleted file mode 100644 index f73474b91..000000000 Binary files a/public/images/team/sam.jpg and /dev/null differ diff --git a/public/images/team/sathya.jpg b/public/images/team/sathya.jpg deleted file mode 100644 index 0f087f4a3..000000000 Binary files a/public/images/team/sathya.jpg and /dev/null differ diff --git a/public/images/team/tianyu.jpg b/public/images/team/tianyu.jpg deleted file mode 100644 index aeb6ed9fa..000000000 Binary files a/public/images/team/tianyu.jpg and /dev/null differ diff --git a/public/js/jsfiddle-integration-babel.js b/public/js/jsfiddle-integration-babel.js index 006c79c8a..56059472f 100644 --- a/public/js/jsfiddle-integration-babel.js +++ b/public/js/jsfiddle-integration-babel.js @@ -4,12 +4,14 @@ // Do not delete or move this file. // Many fiddles reference it so we have to keep it here. -(function() { +(function () { var tag = document.querySelector( 'script[type="application/javascript;version=1.7"]' ); if (!tag || tag.textContent.indexOf('window.onload=function(){') !== -1) { - alert('Bad JSFiddle configuration, please fork the original React JSFiddle'); + alert( + 'Bad JSFiddle configuration, please fork the original React JSFiddle' + ); } tag.setAttribute('type', 'text/babel'); tag.textContent = tag.textContent.replace(/^\/\/ Checks all files and causes an error if heading ID is missing * yarn lint-heading-ids --fix --> Fixes all markdown file's heading IDs * yarn lint-heading-ids path/to/markdown.md --> Checks that particular file for missing heading ID (path can denote a directory or particular file) * yarn lint-heading-ids --fix path/to/markdown.md --> Fixes that particular file's markdown IDs (path can denote a directory or particular file) -*/ + */ const markdownPaths = process.argv.slice(2); if (markdownPaths.includes('--fix')) { diff --git a/src/components/ExternalLink.tsx b/src/components/ExternalLink.tsx index 38b1f2c5f..13fe6d3a9 100644 --- a/src/components/ExternalLink.tsx +++ b/src/components/ExternalLink.tsx @@ -1,13 +1,17 @@ /* * Copyright (c) Facebook, Inc. and its affiliates. */ +import type {DetailedHTMLProps, AnchorHTMLAttributes} from 'react'; export function ExternalLink({ href, target, children, ...props -}: JSX.IntrinsicElements['a']) { +}: DetailedHTMLProps< + AnchorHTMLAttributes, + HTMLAnchorElement +>) { return ( {children} diff --git a/src/components/Icon/IconArrow.tsx b/src/components/Icon/IconArrow.tsx index 714cccd82..61e4e52cd 100644 --- a/src/components/Icon/IconArrow.tsx +++ b/src/components/Icon/IconArrow.tsx @@ -4,9 +4,10 @@ import {memo} from 'react'; import cn from 'classnames'; +import type {SVGProps} from 'react'; export const IconArrow = memo< - JSX.IntrinsicElements['svg'] & { + SVGProps & { /** * The direction the arrow should point. * `start` and `end` are relative to the current locale. diff --git a/src/components/Icon/IconArrowSmall.tsx b/src/components/Icon/IconArrowSmall.tsx index 6653dc387..4a3d3ad02 100644 --- a/src/components/Icon/IconArrowSmall.tsx +++ b/src/components/Icon/IconArrowSmall.tsx @@ -4,9 +4,10 @@ import {memo} from 'react'; import cn from 'classnames'; +import type {SVGProps} from 'react'; export const IconArrowSmall = memo< - JSX.IntrinsicElements['svg'] & { + SVGProps & { /** * The direction the arrow should point. * `start` and `end` are relative to the current locale. diff --git a/src/components/Icon/IconBsky.tsx b/src/components/Icon/IconBsky.tsx new file mode 100644 index 000000000..5d461556f --- /dev/null +++ b/src/components/Icon/IconBsky.tsx @@ -0,0 +1,23 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + */ + +import {memo} from 'react'; +import type {SVGProps} from 'react'; + +export const IconBsky = memo>(function IconBsky(props) { + return ( + + + + ); +}); diff --git a/src/components/Icon/IconClose.tsx b/src/components/Icon/IconClose.tsx index 5ad352cf0..d685fb217 100644 --- a/src/components/Icon/IconClose.tsx +++ b/src/components/Icon/IconClose.tsx @@ -3,8 +3,9 @@ */ import {memo} from 'react'; +import type {SVGProps} from 'react'; -export const IconClose = memo(function IconClose( +export const IconClose = memo>(function IconClose( props ) { return ( 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/Icon/IconFacebookCircle.tsx b/src/components/Icon/IconFacebookCircle.tsx index 0900d6815..7f1080afa 100644 --- a/src/components/Icon/IconFacebookCircle.tsx +++ b/src/components/Icon/IconFacebookCircle.tsx @@ -3,8 +3,9 @@ */ import {memo} from 'react'; +import type {SVGProps} from 'react'; -export const IconFacebookCircle = memo( +export const IconFacebookCircle = memo>( function IconFacebookCircle(props) { return ( ( - function IconGitHub(props) { - return ( - - - - ); - } -); +export const IconGitHub = memo>(function IconGitHub( + props +) { + return ( + + + + ); +}); diff --git a/src/components/Icon/IconHamburger.tsx b/src/components/Icon/IconHamburger.tsx index 5e6aa725a..8bc90ee0c 100644 --- a/src/components/Icon/IconHamburger.tsx +++ b/src/components/Icon/IconHamburger.tsx @@ -3,8 +3,9 @@ */ import {memo} from 'react'; +import type {SVGProps} from 'react'; -export const IconHamburger = memo( +export const IconHamburger = memo>( function IconHamburger(props) { return ( ( +export const IconInstagram = memo>( function IconInstagram(props) { return ( (function IconLink( - props -) { +export const IconLink = memo>(function IconLink(props) { return ( ( - function IconNewPage(props) { - return ( - - - - - ); - } -); +export const IconNewPage = memo>(function IconNewPage( + props +) { + return ( + + + + + ); +}); diff --git a/src/components/Icon/IconRocket.tsx b/src/components/Icon/IconRocket.tsx new file mode 100644 index 000000000..457736c7c --- /dev/null +++ b/src/components/Icon/IconRocket.tsx @@ -0,0 +1,32 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + */ + +import {memo} from 'react'; + +export const IconRocket = memo< + JSX.IntrinsicElements['svg'] & {title?: string; size?: 's' | 'md'} +>(function IconRocket({className, size = 'md'}) { + return ( + + ); +}); diff --git a/src/components/Icon/IconRss.tsx b/src/components/Icon/IconRss.tsx index f2a52ee25..6208236f4 100644 --- a/src/components/Icon/IconRss.tsx +++ b/src/components/Icon/IconRss.tsx @@ -3,10 +3,9 @@ */ import {memo} from 'react'; +import type {SVGProps} from 'react'; -export const IconRss = memo(function IconRss( - props -) { +export const IconRss = memo>(function IconRss(props) { return ( ( - function IconSearch(props) { - return ( - - - - ); - } -); +export const IconSearch = memo>(function IconSearch( + props +) { + return ( + + + + ); +}); diff --git a/src/components/Icon/IconThreads.tsx b/src/components/Icon/IconThreads.tsx index 5a007657f..9ea0bafdf 100644 --- a/src/components/Icon/IconThreads.tsx +++ b/src/components/Icon/IconThreads.tsx @@ -3,22 +3,23 @@ */ import {memo} from 'react'; +import type {SVGProps} from 'react'; -export const IconThreads = memo( - function IconThreads(props) { - return ( - - - - ); - } -); +export const IconThreads = memo>(function IconThreads( + props +) { + return ( + + + + ); +}); diff --git a/src/components/Icon/IconTwitter.tsx b/src/components/Icon/IconTwitter.tsx index e7b0cf09e..e84971f4e 100644 --- a/src/components/Icon/IconTwitter.tsx +++ b/src/components/Icon/IconTwitter.tsx @@ -3,20 +3,21 @@ */ import {memo} from 'react'; +import type {SVGProps} from 'react'; -export const IconTwitter = memo( - function IconTwitter(props) { - return ( - - - - - ); - } -); +export const IconTwitter = memo>(function IconTwitter( + props +) { + return ( + + + + + ); +}); diff --git a/src/components/Layout/Footer.tsx b/src/components/Layout/Footer.tsx index 5bcf9df98..9cdf256fb 100644 --- a/src/components/Layout/Footer.tsx +++ b/src/components/Layout/Footer.tsx @@ -8,6 +8,7 @@ import cn from 'classnames'; import {ExternalLink} from 'components/ExternalLink'; import {IconFacebookCircle} from 'components/Icon/IconFacebookCircle'; import {IconTwitter} from 'components/Icon/IconTwitter'; +import {IconBsky} from 'components/Icon/IconBsky'; import {IconGitHub} from 'components/Icon/IconGitHub'; export function Footer() { @@ -283,7 +284,7 @@ export function Footer() {
- ©{new Date().getFullYear()} + Copyright © Meta Platforms, Inc
+ + +
+ 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}
{title}{' '} - {canary && ( + {version === 'major' && ( + + React 19 + + )} + {version === 'canary' && ( + )} + {version === 'experimental' && ( + )}
diff --git a/src/components/Layout/Sidebar/SidebarRouteTree.tsx b/src/components/Layout/Sidebar/SidebarRouteTree.tsx index 3f058073c..72003df74 100644 --- a/src/components/Layout/Sidebar/SidebarRouteTree.tsx +++ b/src/components/Layout/Sidebar/SidebarRouteTree.tsx @@ -38,6 +38,7 @@ function CollapseWrapper({ // Disable pointer events while animating. const isExpandedRef = useRef(isExpanded); if (typeof window !== 'undefined') { + // eslint-disable-next-line react-compiler/react-compiler // eslint-disable-next-line react-hooks/rules-of-hooks useLayoutEffect(() => { const wasExpanded = isExpandedRef.current; @@ -87,7 +88,7 @@ export function SidebarRouteTree({ path, title, routes, - canary, + version, heading, hasSectionHeader, sectionHeader, @@ -121,7 +122,7 @@ export function SidebarRouteTree({ selected={selected} level={level} title={title} - canary={canary} + version={version} isExpanded={isExpanded} hideArrow={isForceExpanded} /> @@ -145,7 +146,7 @@ export function SidebarRouteTree({ selected={selected} level={level} title={title} - canary={canary} + version={version} /> ); diff --git a/src/components/Layout/TopNav/BrandMenu.tsx b/src/components/Layout/TopNav/BrandMenu.tsx new file mode 100644 index 000000000..3bd8776f2 --- /dev/null +++ b/src/components/Layout/TopNav/BrandMenu.tsx @@ -0,0 +1,145 @@ +import * as ContextMenu from '@radix-ui/react-context-menu'; +import {IconCopy} from 'components/Icon/IconCopy'; +import {IconDownload} from 'components/Icon/IconDownload'; +import {IconNewPage} from 'components/Icon/IconNewPage'; +import {ExternalLink} from 'components/ExternalLink'; +import {IconClose} from '../../Icon/IconClose'; + +function MenuItem({ + children, + onSelect, +}: { + children: React.ReactNode; + onSelect?: () => void; +}) { + return ( + + {children} + + ); +} + +function DownloadMenuItem({ + fileName, + href, + children, +}: { + fileName: string; + href: string; + children: React.ReactNode; +}) { + return ( +
+ {children} + + ); +} + +export default function BrandMenu({children}: {children: React.ReactNode}) { + return ( + + + {children} + + + + + Dark Mode + + + + + + Logo SVG + + + + + + Wordmark SVG + + { + await navigator.clipboard.writeText('#58C4DC'); + }}> + + + + Copy dark mode color + + + Light Mode + + + + + + Logo SVG + + + + + + Wordmark SVG + + { + await navigator.clipboard.writeText('#087EA4'); + }}> + + + + Copy light mode color + +
+ + + uwu + + { + // @ts-ignore + window.__setUwu(false); + }}> + + + + Turn off + + + + + + Logo PNG + + + + + + + + Logo by @sawaratsuki1004 + + +
+
+
+
+ ); +} diff --git a/src/components/Layout/TopNav/TopNav.tsx b/src/components/Layout/TopNav/TopNav.tsx index c93992e59..cc5c654e3 100644 --- a/src/components/Layout/TopNav/TopNav.tsx +++ b/src/components/Layout/TopNav/TopNav.tsx @@ -26,6 +26,7 @@ import {Feedback} from '../Feedback'; import {SidebarRouteTree} from '../Sidebar'; import type {RouteItem} from '../getRouteMeta'; import {siteConfig} from 'siteConfig'; +import BrandMenu from './BrandMenu'; declare global { interface Window { @@ -125,7 +126,7 @@ function NavItem({url, isActive, children}: any) {
}> + +
+ {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. */} + +
+
{children}
+
+
+
+ ); +} +``` + +```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 ( + + ); +} +``` + +```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 ( + + + + ); +} + +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 ( +
e.preventDefault()}> + +
+
+ +
+ onChange(e.target.value)} + /> +
+
+ ); +} + +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. */} + +
+
{children}
+
+
+
+ ); +} +``` + +```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 ( + + ); +} +``` + +```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 ( + + + + ); +} + +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 ( +
e.preventDefault()}> + +
+
+ +
+ onChange(e.target.value)} + /> +
+
+ ); +} + +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. */} + +
+
{children}
+
+
+
+ ); +} +``` + +```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 ( + + ); +} +``` + +```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 ( + + + + ); +} + +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 ( +
e.preventDefault()}> + +
+
+ +
+ onChange(e.target.value)} + /> +
+
+ ); +} + +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. */} + +
+
{children}
+
+
+
+ ); +} +``` + +```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 ( + + ); +} +``` + +```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 ( + + + + ); +} + + + +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 ( +
e.preventDefault()}> + +
+
+ +
+ onChange(e.target.value)} + /> +
+
+ ); +} + +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. */} + +
+
{children}
+
+
+
+ ); +} +``` + +```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 ( + + ); +} +``` + +```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 ( + + + + ); +} + +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 ( +
e.preventDefault()}> + +
+
+ +
+ onChange(e.target.value)} + /> +
+
+ ); +} + +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. */} + +
+
{children}
+
+
+
+ ); +} +``` + +```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 ( + + ); +} +``` + +```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 ( + + + + ); +} + +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 245559028..a7a897634 100644 --- a/src/content/blog/index.md +++ b/src/content/blog/index.md @@ -4,21 +4,53 @@ 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. You can also follow the [@reactjs](https://twitter.com/reactjs) account on Twitter, but you won’t miss anything essential if you only read this 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. + +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.
- + + +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 ... + + + + + +In the React 19 Upgrade Guide, we shared step-by-step instructions for upgrading your app to React 19. In this post, we'll give an overview of the new features in React 19, and how you can adopt them ... + + + + + +We announced an experimental release of React Compiler at React Conf 2024. We've made a lot of progress since then, and in this post we want to share what's next for React Compiler ... + + + + -In the React 19 Beta Upgrade Guide, we shared step-by-step instructions for upgrading your app to React 19 Beta. In this post, we'll give an overview of the new features in React 19, and how you can adopt them. +Last week we hosted React Conf 2024, a two-day conference in Henderson, Nevada where 700+ attendees gathered in-person to discuss the latest in UI engineering. This was our first in-person conference since 2019, and we were thrilled to be able to bring the community together again ... - + -The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading libraries to React 19 beta. +The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible, and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading libraries to React 19 ... diff --git a/src/content/community/acknowledgements.md b/src/content/community/acknowledgements.md index aeb0787ef..bfe67f55a 100644 --- a/src/content/community/acknowledgements.md +++ b/src/content/community/acknowledgements.md @@ -4,7 +4,7 @@ title: Acknowledgements -React was originally created by [Jordan Walke.](https://github.com/jordwalke) Today, React has a [dedicated full-time team working on it](/community/team), as well as over a thousand [open source contributors.](https://github.com/facebook/react/blob/main/AUTHORS) +React was originally created by [Jordan Walke.](https://github.com/jordwalke) Today, React has a [dedicated full-time team working on it](/community/team), as well as over a thousand [open source contributors.](https://github.com/facebook/react/graphs/contributors) @@ -36,6 +36,8 @@ We'd like to recognize a few people who have made significant contributions to R * [Joe Critchley](https://github.com/joecritch) * [Jeff Morrison](https://github.com/jeffmo) * [Luna Ruan](https://github.com/lunaruan) +* [Luna Wei](https://github.com/lunaleaps) +* [Noah Lemen](https://github.com/noahlemen) * [Kathryn Middleton](https://github.com/kmiddleton14) * [Keyan Zhang](https://github.com/keyz) * [Marco Salazar](https://github.com/salazarm) @@ -51,15 +53,16 @@ We'd like to recognize a few people who have made significant contributions to R * [Samuel Susla](https://github.com/sammy-SC) * [Sander Spies](https://github.com/sanderspies) * [Sasha Aickin](https://github.com/aickin) -* [Sean Keegan](https://github.com/seanryankeegan) +* [Sathya Gunasekaran](https://github.com/gsathya) * [Sophia Shoemaker](https://github.com/mrscobbler) * [Sunil Pai](https://github.com/threepointone) +* [Tianyu Yao](https://github.com/) * [Tim Yung](https://github.com/yungsters) * [Xuan Huang](https://github.com/huxpro) This list is not exhaustive. -We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages.](https://translations.reactjs.org/) +We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages.](https://translations.react.dev/) ## Additional Thanks {/*additional-thanks*/} diff --git a/src/content/community/conferences.md b/src/content/community/conferences.md index dc0d60c58..a2bcd196e 100644 --- a/src/content/community/conferences.md +++ b/src/content/community/conferences.md @@ -10,98 +10,199 @@ Do you know of a local React.js conference? Add it here! (Please keep the list c ## Upcoming Conferences {/*upcoming-conferences*/} -### React Paris 2024 {/*react-paris-2024*/} -March 22, 2024. In-person in Paris, France + Remote (hybrid) +### CityJS London 2025 {/*cityjs-london*/} +April 23 - 25, 2025. In-person in London, UK -[Website](https://react.paris/) - [Twitter](https://twitter.com/BeJS_) - [LinkedIn](https://www.linkedin.com/events/7150816372074192900/comments/) +[Website](https://london.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) -### Epic Web Conf 2024 {/*epic-web-2024*/} -April 10 - 11, 2024. In-person in Park City, UT, USA +### App.js Conf 2025 {/*appjs-conf-2025*/} +May 28 - 30, 2025. In-person in Kraków, Poland + remote -[Website](https://www.epicweb.dev/conf) - [YouTube](https://www.youtube.com/@EpicWebDev) +[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf) -### React Miami 2024 {/*react-miami-2024*/} -April 19 - 20, 2024. In-person in Miami, FL, USA +### CityJS Athens 2025 {/*cityjs-athens*/} +May 27 - 31, 2025. In-person in Athens, Greece -[Website](https://reactmiami.com/) - [Twitter](https://twitter.com/ReactMiamiConf) +[Website](https://athens.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) -### React Connection 2024 {/*react-connection-2024*/} -April 22, 2024. In-person in Paris, France +### React Norway 2025 {/*react-norway-2025*/} +June 13, 2025. In-person in Oslo, Norway + remote (virtual event) -[Website](https://reactconnection.io/) - [Twitter](https://twitter.com/ReactConn) +[Website](https://reactnorway.com/) - [Twitter](https://x.com/ReactNorway) -### React Native Connection 2024 {/*react-native-connection-2024*/} -April 23, 2024. In-person in Paris, France +### React Summit 2025 {/*react-summit-2025*/} +June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event) -[Website](https://reactnativeconnection.io/) - [Twitter](https://twitter.com/ReactNativeConn) +[Website](https://reactsummit.com/) - [Twitter](https://x.com/reactsummit) -### React Conf 2024 {/*react-conf-2024*/} -May 15 - 16, 2024. In-person in Henderson, NV, USA + remote +### React Nexus 2025 {/*react-nexus-2025*/} +July 03 - 05, 2025. In-person in Bangalore, India -[Website](https://conf.react.dev) - [Twitter](https://twitter.com/reactjs) +[Website](https://reactnexus.com/) - [Twitter](https://x.com/ReactNexus) - [Bluesky](https://bsky.app/profile/reactnexus.com) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) -### App.js Conf 2024 {/*appjs-conf-2024*/} -May 22 - 24, 2024. In-person in Kraków, Poland + remote +### React Universe Conf 2025 {/*react-universe-conf-2025*/} +September 2-4, 2025. Wrocław, Poland. -[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf) +[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/) -### Frontend Nation 2024 {/*frontend-nation-2024*/} -June 4 - 7, 2024. Online +### React Conf 2025 {/*react-conf-2025*/} +October 7-8, 2025. Henderson, Nevada, USA and free livestream -[Website](https://frontendnation.com/) - [Twitter](https://twitter.com/frontendnation) +[Website](https://conf.react.dev/) - [Twitter](https://x.com/reactjs) - [Bluesky](https://bsky.app/profile/react.dev) + +### React India 2025 {/*react-india-2025*/} +October 31 - November 01, 2025. In-person in Goa, India (hybrid event) + Oct 15 2025 - remote day + +[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*/} + +### React Paris 2025 {/*react-paris-2025*/} +March 20 - 21, 2025. In-person in Paris, France (hybrid event) + +[Website](https://react.paris/) - [Twitter](https://x.com/BeJS_) + +### React Native Connection 2025 {/*react-native-connection-2025*/} +April 3 (Reanimated Training) + April 4 (Conference), 2025. Paris, France. + +[Website](https://reactnativeconnection.io/) - [X](https://x.com/reactnativeconn) - [Bluesky](https://bsky.app/profile/reactnativeconnect.bsky.social) + +### React Day Berlin 2024 {/*react-day-berlin-2024*/} +December 13 & 16, 2024. In-person in Berlin, Germany + remote (hybrid event) + +[Website](https://reactday.berlin/) - [Twitter](https://x.com/reactdayberlin) + +### React Africa 2024 {/*react-africa-2024*/} +November 29, 2024. In-person in Casablanca, Morocco (hybrid event) + +[Website](https://react-africa.com/) - [Twitter](https://x.com/BeJS_) + +### React Summit US 2024 {/*react-summit-us-2024*/} +November 19 & 22, 2024. In-person in New York, USA + online (hybrid event) + +[Website](https://reactsummit.us/) - [Twitter](https://twitter.com/reactsummit) - [Videos](https://portal.gitnation.org/) + +### React Native London Conf 2024 {/*react-native-london-2024*/} +November 14 & 15, 2024. In-person in London, UK + +[Website](https://reactnativelondon.co.uk/) - [Twitter](https://x.com/RNLConf) + +### React Advanced London 2024 {/*react-advanced-london-2024*/} +October 25 & 28, 2024. In-person in London, UK + online (hybrid event) + +[Website](https://reactadvanced.com/) - [Twitter](https://x.com/reactadvanced) + +### reactjsday 2024 {/*reactjsday-2024*/} +October 25, 2024. In-person in Verona, Italy + online (hybrid event) + +[Website](https://2024.reactjsday.it/) - [Twitter](https://x.com/reactjsday) - [Facebook](https://www.facebook.com/GrUSP/) - [YouTube](https://www.youtube.com/c/grusp) + +### React Brussels 2024 {/*react-brussels-2024*/} +October 18, 2024. In-person in Brussels, Belgium (hybrid event) + +[Website](https://www.react.brussels/) - [Twitter](https://x.com/BrusselsReact) - [YouTube](https://www.youtube.com/playlist?list=PL53Z0yyYnpWimQ0U75woee2zNUIFsiDC3) + +### React India 2024 {/*react-india-2024*/} +October 17 - 19, 2024. In-person in Goa, India (hybrid event) + Oct 15 2024 - remote day + +[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) + +### RenderCon Kenya 2024 {/*rendercon-kenya-2024*/} +October 04 - 05, 2024. Nairobi, Kenya + +[Website](https://rendercon.org/) - [Twitter](https://twitter.com/renderconke) - [LinkedIn](https://www.linkedin.com/company/renderconke/) - [YouTube](https://www.youtube.com/channel/UC0bCcG8gHUL4njDOpQGcMIA) + +### React Alicante 2024 {/*react-alicante-2024*/} +September 19-21, 2024. Alicante, Spain. + +[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/ReactAlicante) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w) + +### React Universe Conf 2024 {/*react-universe-conf-2024*/} +September 5-6, 2024. Wrocław, Poland. + +[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/) + + +### React Rally 2024 🐙 {/*react-rally-2024*/} +August 12-13, 2024. Park City, UT, USA + +[Website](https://reactrally.com) - [Twitter](https://twitter.com/ReactRally) - [YouTube](https://www.youtube.com/channel/UCXBhQ05nu3L1abBUGeQ0ahw) + +### The Geek Conf 2024 {/*the-geek-conf-2024*/} +July 25, 2024. In-person in Berlin, Germany + remote (hybrid event) + +[Website](https://thegeekconf.com) - [Twitter](https://twitter.com/thegeekconf) + +### Chain React 2024 {/*chain-react-2024*/} +July 17-19, 2024. In-person in Portland, OR, USA + +[Website](https://chainreactconf.com) - [Twitter](https://twitter.com/ChainReactConf) + +### React Nexus 2024 {/*react-nexus-2024*/} +July 04 & 05, 2024. Bangalore, India (In-person event) + +[Website](https://reactnexus.com/) - [Twitter](https://twitter.com/ReactNexus) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) ### React Summit 2024 {/*react-summit-2024*/} June 14 & 18, 2024. In-person in Amsterdam, Netherlands + remote (hybrid event) [Website](https://reactsummit.com/) - [Twitter](https://twitter.com/reactsummit) - [Videos](https://portal.gitnation.org/) -### Render(ATL) 2024 🍑 {/*renderatl-2024-*/} -June 12 - June 14, 2024. Atlanta, GA, USA - -[Website](https://renderatl.com) - [Discord](https://www.renderatl.com/discord) - [Twitter](https://twitter.com/renderATL) - [Instagram](https://www.instagram.com/renderatl/) - [Facebook](https://www.facebook.com/renderatl/) - [LinkedIn](https://www.linkedin.com/company/renderatl) - [Podcast](https://www.renderatl.com/culture-and-code#/) - ### React Norway 2024 {/*react-norway-2024*/} June 14, 2024. In-person at Farris Bad Hotel in Larvik, Norway and online (hybrid event). [Website](https://reactnorway.com/) - [Twitter](https://twitter.com/ReactNorway) -### React Nexus 2024 {/*react-nexus-2024*/} -July 04 & 05, 2024. Bangalore, India (In-person event) +### Render(ATL) 2024 🍑 {/*renderatl-2024-*/} +June 12 - June 14, 2024. Atlanta, GA, USA -[Website](https://reactnexus.com/) - [Twitter](https://twitter.com/ReactNexus) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) +[Website](https://renderatl.com) - [Discord](https://www.renderatl.com/discord) - [Twitter](https://twitter.com/renderATL) - [Instagram](https://www.instagram.com/renderatl/) - [Facebook](https://www.facebook.com/renderatl/) - [LinkedIn](https://www.linkedin.com/company/renderatl) - [Podcast](https://www.renderatl.com/culture-and-code#/) -### Chain React 2024 {/*chain-react-2024*/} -July 17-19, 2024. In-person in Portland, OR, USA +### Frontend Nation 2024 {/*frontend-nation-2024*/} +June 4 - 7, 2024. Online -[Website](https://chainreactconf.com) - [Twitter](https://twitter.com/ChainReactConf) +[Website](https://frontendnation.com/) - [Twitter](https://twitter.com/frontendnation) -### The Geek Conf 2024 {/*the-geek-conf-2024*/} -July 25, 2024. In-person in Berlin, Germany + remote (hybrid event) +### App.js Conf 2024 {/*appjs-conf-2024*/} +May 22 - 24, 2024. In-person in Kraków, Poland + remote -[Website](https://thegeekconf.com) - [Twitter](https://twitter.com/thegeekconf) +[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf) -### React Rally 2024 🐙 {/*react-rally-2024*/} -August 12-13, 2024. Park City, UT, USA +### React Conf 2024 {/*react-conf-2024*/} +May 15 - 16, 2024. In-person in Henderson, NV, USA + remote -[Website](https://reactrally.com) - [Twitter](https://twitter.com/ReactRally) - [YouTube](https://www.youtube.com/channel/UCXBhQ05nu3L1abBUGeQ0ahw) +[Website](https://conf.react.dev) - [Twitter](https://twitter.com/reactjs) -### React Universe Conf 2024 {/*react-universe-conf-2024*/} -September 5-6, 2024. Wrocław, Poland. +### React Native Connection 2024 {/*react-native-connection-2024*/} +April 23, 2024. In-person in Paris, France -[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/) +[Website](https://reactnativeconnection.io/) - [Twitter](https://twitter.com/ReactNativeConn) -### React Alicante 2024 {/*react-alicante-2024*/} -September 19-21, 2024. Alicante, Spain. +### React Miami 2024 {/*react-miami-2024*/} +April 19 - 20, 2024. In-person in Miami, FL, USA -[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/ReactAlicante) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w) +[Website](https://reactmiami.com/) - [Twitter](https://twitter.com/ReactMiamiConf) +### Epic Web Conf 2024 {/*epic-web-2024*/} +April 10 - 11, 2024. In-person in Park City, UT, USA -### React India 2024 {/*react-india-2024*/} -October 17 - 19, 2024. In-person in Goa, India (hybrid event) + Oct 15 2024 - remote day +[Website](https://www.epicweb.dev/conf) - [YouTube](https://www.youtube.com/@EpicWebDev) -[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 Paris 2024 {/*react-paris-2024*/} +March 22, 2024. In-person in Paris, France + Remote (hybrid) -## Past Conferences {/*past-conferences*/} +[Website](https://react.paris/) - [Twitter](https://twitter.com/BeJS_) - [LinkedIn](https://www.linkedin.com/events/7150816372074192900/comments/) - [Videos](https://www.youtube.com/playlist?list=PL53Z0yyYnpWhUzgvr2Nys3kZBBLcY0TA7) ### React Day Berlin 2023 {/*react-day-berlin-2023*/} December 8 & 12, 2023. In-person in Berlin, Germany + remote first interactivity (hybrid event) diff --git a/src/content/community/docs-contributors.md b/src/content/community/docs-contributors.md index 0f9d002d6..27b32a18f 100644 --- a/src/content/community/docs-contributors.md +++ b/src/content/community/docs-contributors.md @@ -11,7 +11,7 @@ React documentation is written and maintained by the [React team](/community/tea ## Content {/*content*/} * [Rachel Nabors](https://twitter.com/RachelNabors): editing, writing, illustrating -* [Dan Abramov](https://twitter.com/dan_abramov): writing, curriculum design +* [Dan Abramov](https://bsky.app/profile/danabra.mov): writing, curriculum design * [Sylwia Vargas](https://twitter.com/SylwiaVargas): example code * [Rick Hanlon](https://twitter.com/rickhanlonii): writing * [David McCabe](https://twitter.com/mcc_abe): writing @@ -34,7 +34,7 @@ React documentation is written and maintained by the [React team](/community/tea * [Jared Palmer](https://twitter.com/jaredpalmer): site development * [ThisDotLabs](https://www.thisdot.co/) ([Dane Grant](https://twitter.com/danecando), [Dustin Goodman](https://twitter.com/dustinsgoodman)): site development * [CodeSandbox](https://codesandbox.io/) ([Ives van Hoorne](https://twitter.com/CompuIves), [Alex Moldovan](https://twitter.com/alexnmoldovan), [Jasper De Moor](https://twitter.com/JasperDeMoor), [Danilo Woznica](https://twitter.com/danilowoz)): sandbox integration -* [Dan Abramov](https://twitter.com/dan_abramov): site development +* [Dan Abramov](https://bsky.app/profile/danabra.mov): site development * [Rick Hanlon](https://twitter.com/rickhanlonii): site development * [Harish Kumar](https://www.strek.in/): development and maintenance * [Luna Ruan](https://twitter.com/lunaruan): sandbox improvements 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 a12a5349c..81fc5c210 100644 --- a/src/content/community/meetups.md +++ b/src/content/community/meetups.md @@ -30,53 +30,40 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Belo Horizonte](https://www.meetup.com/reactbh/) * [Curitiba](https://www.meetup.com/pt-br/ReactJS-CWB/) * [Florianópolis](https://www.meetup.com/pt-br/ReactJS-Floripa/) -* [Goiânia](https://www.meetup.com/pt-br/React-Goiania/) * [Joinville](https://www.meetup.com/pt-BR/React-Joinville/) -* [Juiz de Fora](https://www.meetup.com/pt-br/React-Juiz-de-Fora/) -* [Maringá](https://www.meetup.com/pt-BR/React-Maringa/) -* [Porto Alegre](https://www.meetup.com/pt-BR/React-Porto-Alegre/) -* [Rio de Janeiro](https://www.meetup.com/pt-BR/React-Rio-de-Janeiro/) -* [Salvador](https://www.meetup.com/pt-BR/ReactSSA) * [São Paulo](https://www.meetup.com/pt-BR/ReactJS-SP/) -* [Vila Velha](https://www.meetup.com/pt-BR/React-ES/) ## Bolivia {/*bolivia*/} * [Bolivia](https://www.meetup.com/ReactBolivia/) ## 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/) * [Toronto, ON](https://www.meetup.com/Toronto-React-Native/events/) -## Chile {/*chile*/} -* [Santiago](https://www.meetup.com/es-ES/react-santiago/) - -## China {/*china*/} -* [Beijing](https://www.meetup.com/Beijing-ReactJS-Meetup/) - ## Colombia {/*colombia*/} -* [Bogotá](https://www.meetup.com/meetup-group-iHIeHykY/) * [Medellin](https://www.meetup.com/React-Medellin/) -* [Cali](https://www.meetup.com/reactcali/) + +## Czechia {/*czechia*/} +* [Prague](https://guild.host/react-prague/) ## Denmark {/*denmark*/} * [Aalborg](https://www.meetup.com/Aalborg-React-React-Native-Meetup/) * [Aarhus](https://www.meetup.com/Aarhus-ReactJS-Meetup/) -## Egypt {/*egypt*/} -* [Cairo](https://www.meetup.com/react-cairo/) - ## England (UK) {/*england-uk*/} * [Manchester](https://www.meetup.com/Manchester-React-User-Group/) * [React.JS Girls London](https://www.meetup.com/ReactJS-Girls-London/) * [React Advanced London](https://guild.host/react-advanced-london) * [React Native London](https://guild.host/RNLDN) +## Finland {/*finland*/} +* [Helsinki](https://www.meetabit.com/communities/react-helsinki) + ## France {/*france*/} -* [Nantes](https://www.meetup.com/React-Nantes/) * [Lille](https://www.meetup.com/ReactBeerLille/) * [Paris](https://www.meetup.com/ReactJS-Paris/) @@ -93,14 +80,11 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Athens](https://www.meetup.com/React-To-React-Athens-MeetUp/) * [Thessaloniki](https://www.meetup.com/Thessaloniki-ReactJS-Meetup/) -## Hungary {/*hungary*/} -* [Budapest](https://www.meetup.com/React-Budapest/) - ## India {/*india*/} -* [Ahmedabad](https://www.meetup.com/react-ahmedabad/) +* [Ahmedabad](https://reactahmedabad.dev/) * [Bangalore (React)](https://www.meetup.com/ReactJS-Bangalore/) * [Bangalore (React Native)](https://www.meetup.com/React-Native-Bangalore-Meetup) -* [Chennai](https://www.meetup.com/React-Chennai/) +* [Chennai](https://www.linkedin.com/company/chennaireact) * [Delhi NCR](https://www.meetup.com/React-Delhi-NCR/) * [Mumbai](https://reactmumbai.dev) * [Pune](https://www.meetup.com/ReactJS-and-Friends/) @@ -117,6 +101,9 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet ## Italy {/*italy*/} * [Milan](https://www.meetup.com/React-JS-Milano/) +## Japan {/*japan*/} +* [Osaka](https://react-osaka.connpass.com/) + ## Kenya {/*kenya*/} * [Nairobi - Reactdevske](https://kommunity.com/reactjs-developer-community-kenya-reactdevske) @@ -138,12 +125,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Karachi](https://www.facebook.com/groups/902678696597634/) * [Lahore](https://www.facebook.com/groups/ReactjsLahore/) -## Panama {/*panama*/} -* [Panama](https://www.meetup.com/React-Panama/) - -## Peru {/*peru*/} -* [Lima](https://www.meetup.com/ReactJS-Peru/) - ## Philippines {/*philippines*/} * [Manila](https://www.meetup.com/reactjs-developers-manila/) * [Manila - ReactJS PH](https://www.meetup.com/ReactJS-Philippines/) @@ -160,7 +141,9 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet ## Spain {/*spain*/} * [Barcelona](https://www.meetup.com/ReactJS-Barcelona/) -* [Canarias](https://www.meetup.com/React-Canarias/) + +## Sri Lanka {/*sri-lanka*/} +* [Colombo](https://www.javascriptcolombo.com/) ## Sweden {/*sweden*/} * [Goteborg](https://www.meetup.com/ReactJS-Goteborg/) @@ -176,7 +159,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Kyiv](https://www.meetup.com/Kyiv-ReactJS-Meetup) ## US {/*us*/} -* [Ann Arbor, MI - ReactJS](https://www.meetup.com/AnnArbor-jsx/) * [Atlanta, GA - ReactJS](https://www.meetup.com/React-ATL/) * [Austin, TX - ReactJS](https://www.meetup.com/ReactJS-Austin-Meetup/) * [Boston, MA - ReactJS](https://www.meetup.com/ReactJS-Boston/) @@ -187,7 +169,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Cleveland, OH - ReactJS](https://www.meetup.com/Cleveland-React/) * [Columbus, OH - ReactJS](https://www.meetup.com/ReactJS-Columbus-meetup/) * [Dallas, TX - ReactJS](https://www.meetup.com/ReactDallas/) -* [Dallas, TX - [Remote] React JS](https://www.meetup.com/React-JS-Group/) +* [Denver, CO - React Denver](https://reactdenver.com/) * [Detroit, MI - Detroit React User Group](https://www.meetup.com/Detroit-React-User-Group/) * [Indianapolis, IN - React.Indy](https://www.meetup.com/React-Indy) * [Irvine, CA - ReactJS](https://www.meetup.com/ReactJS-OC/) @@ -197,27 +179,19 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Los Angeles, CA - ReactJS](https://www.meetup.com/socal-react/) * [Los Angeles, CA - React Native](https://www.meetup.com/React-Native-Los-Angeles/) * [Miami, FL - ReactJS](https://www.meetup.com/React-Miami/) -* [Nashville, TN - ReactJS](https://www.meetup.com/NashReact-Meetup/) * [New York, NY - ReactJS](https://www.meetup.com/NYC-Javascript-React-Group/) * [New York, NY - React Ladies](https://www.meetup.com/React-Ladies/) * [New York, NY - React Native](https://www.meetup.com/React-Native-NYC/) * [New York, NY - useReactNYC](https://www.meetup.com/useReactNYC/) * [New York, NY - React.NYC](https://guild.host/react-nyc) -* [Omaha, NE - ReactJS/React Native](https://www.meetup.com/omaha-react-meetup-group/) * [Palo Alto, CA - React Native](https://www.meetup.com/React-Native-Silicon-Valley/) -* [Philadelphia, PA - ReactJS](https://www.meetup.com/Reactadelphia/) * [Phoenix, AZ - ReactJS](https://www.meetup.com/ReactJS-Phoenix/) -* [Pittsburgh, PA - ReactJS/React Native](https://www.meetup.com/ReactPgh/) -* [Portland, OR - ReactJS](https://www.meetup.com/Portland-ReactJS/) * [Provo, UT - ReactJS](https://www.meetup.com/ReactJS-Utah/) -* [Sacramento, CA - ReactJS](https://www.meetup.com/Sacramento-ReactJS-Meetup/) * [San Diego, CA - San Diego JS](https://www.meetup.com/sandiegojs/) * [San Francisco - Real World React](https://www.meetup.com/Real-World-React) * [San Francisco - ReactJS](https://www.meetup.com/ReactJS-San-Francisco/) * [San Francisco, CA - React Native](https://www.meetup.com/React-Native-San-Francisco/) -* [San Ramon, CA - TriValley Coders](https://www.meetup.com/trivalleycoders/) * [Santa Monica, CA - ReactJS](https://www.meetup.com/Los-Angeles-ReactJS-User-Group/) -* [Seattle, WA - React Native](https://www.meetup.com/Seattle-React-Native-Meetup/) * [Seattle, WA - ReactJS](https://www.meetup.com/seattle-react-js/) * [Tampa, FL - ReactJS](https://www.meetup.com/ReactJS-Tampa-Bay/) * [Tucson, AZ - ReactJS](https://www.meetup.com/Tucson-ReactJS-Meetup/) diff --git a/src/content/community/team.md b/src/content/community/team.md index 6004476e2..da4ce0791 100644 --- a/src/content/community/team.md +++ b/src/content/community/team.md @@ -18,14 +18,18 @@ Current members of the React team are listed in alphabetical order below. Andrew got started with web development by making sites with WordPress, and eventually tricked himself into doing JavaScript. His favorite pastime is karaoke. Andrew is either a Disney villain or a Disney princess, depending on the day. - + Dan got into programming after he accidentally discovered Visual Basic inside Microsoft PowerPoint. He has found his true calling in turning [Sebastian](#sebastian-markbåge)'s tweets into long-form blog posts. Dan occasionally wins at Fortnite by hiding in a bush until the game ends. - + Eli got into programming after he got suspended from middle school for hacking. He has been working on React and React Native since 2017. He enjoys eating treats, especially ice cream and apple pie. You can find Eli trying quirky activities like parkour, indoor skydiving, and aerial silks. + + Hendrik’s journey in tech started in the late 90s when he built his first websites with Netscape Communicator. After earning a diploma in computer science and working at digital agencies, he built a React Server Components bundler and library, paving the way to his role on the Next.js team. Outside of work, he enjoys cycling and tinkering in his workshop. + + Shortly after being introduced to AutoHotkey, Jack had written scripts to automate everything he could think of. When reaching limitations there, he dove headfirst into web app development and hasn't looked back. Most recently, Jack worked on the web platform at Instagram before moving to React. His favorite programming language is JSX. @@ -38,31 +42,35 @@ Current members of the React team are listed in alphabetical order below. Joe was planning to major in math and philosophy but got into computer science after writing physics simulations in Matlab. Prior to React, he worked on Relay, RSocket.js, and the Skip programming language. While he’s not building some sort of reactive system he enjoys running, studying Japanese, and spending time with his family. - - Josh majored in Mathematics and discovered programming while in college. His first professional developer job was to program insurance rate calculations in Microsoft Excel, the paragon of Reactive Programming which must be why he now works on React. In between that time Josh has been an IC, Manager, and Executive at a few startups. outside of work he likes to push his limits with cooking. + + Jordan started coding by building iPhone apps, where he was pushing and popping view controllers before he knew that for-loops were a thing. He enjoys working on technology that developers love, which naturally drew him to React. Outside of work he enjoys reading, kiteboarding, and playing guitar. - - Lauren's programming career peaked when she first discovered the `` tag. She’s been chasing that high ever since. She studied Finance instead of CS in college, so she learned to code using Excel instead of Java. Lauren enjoys dropping cheeky memes in chat, playing video games with her partner, and petting her dog Zelda. + + Josh majored in Mathematics and discovered programming while in college. His first professional developer job was to program insurance rate calculations in Microsoft Excel, the paragon of Reactive Programming which must be why he now works on React. In between that time Josh has been an IC, Manager, and Executive at a few startups. outside of work he likes to push his limits with cooking. - - Luna first learnt the fundamentals of python at the age of 6 from her father. Since then, she has been unstoppable. Luna aspires to be a gen z, and the road to success is paved with environmental advocacy, urban gardening and lots of quality time with her Voo-Doo’d (as pictured). + + Lauren's programming career peaked when she first discovered the `` tag. She’s been chasing that high ever since. She studied Finance instead of CS in college, so she learned to code using Excel. Lauren enjoys dropping cheeky memes in chat, playing video games with her partner, learning Korean, and petting her dog Zelda. Matt stumbled into coding, and since then, has become enamored with creating things in communities that can’t be created alone. Prior to React, he worked on YouTube, the Google Assistant, Fuchsia, and Google Cloud AI and Evernote. When he's not trying to make better developer tools he enjoys the mountains, jazz, and spending time with his family. + + Mike went to grad school dreaming of becoming a professor but realized that he liked building things a lot more than writing grant applications. Mike joined Meta to work on Javascript infrastructure, which ultimately led him to work on the React Compiler. When not hacking on either Javascript or OCaml, Mike can often be found hiking or skiing in the Pacific Northwest. + + Mofei started programming when she realized it can help her cheat in video games. She focused on operating systems in undergrad / grad school, but now finds herself happily tinkering on React. Outside of work, she enjoys debugging bouldering problems and planning her next backpacking trip(s). - - Noah’s interest in UI programming sparked during his education in music technology at NYU. At Meta, he's worked on internal tools, browsers, web performance, and is currently focused on React. Outside of work, Noah can be found tinkering with synthesizers or spending time with his cat. + + Pieter studied building science but after failing to get a job he made himself a website and things escalated from there. At Meta, he enjoys working on performance, languages and now React. When he's not programming you can find him off-road in the mountains. - + Ricky majored in theoretical math and somehow found himself on the React Native team for a couple years before joining the React team. When he's not programming you can find him snowboarding, biking, climbing, golfing, or closing GitHub issues that do not match the issue template. @@ -70,10 +78,6 @@ Current members of the React team are listed in alphabetical order below. Ruslan's introduction to UI programming started when he was a kid by manually editing HTML templates for his custom gaming forums. Somehow, he ended up majoring in Computer Science. He enjoys music, games, and memes. Mostly memes. - - Sathya hated the Dragon Book in school but somehow ended up working on compilers all his career. When he's not compiling React components, he's either drinking coffee or eating yet another Dosa. - - Sebastian majored in psychology. He's usually quiet. Even when he says something, it often doesn't make sense to the rest of us until a few months later. The correct way to pronounce his surname is "mark-boa-geh" but he settled for "mark-beige" out of pragmatism -- and that's how he approaches React. @@ -90,10 +94,6 @@ Current members of the React team are listed in alphabetical order below. Four days after React was released, Sophie rewrote the entirety of her then-current project to use it, which she now realizes was perhaps a bit reckless. After she became the project's #1 committer, she wondered why she wasn't getting paid by Facebook like everyone else was and joined the team officially to lead React through its adolescent years. Though she quit that job years ago, somehow she's still in the team's group chats and “providing value”. - - Tianyu’s interest in computers started as a kid because he loves video games. So he majored in computer science and still plays childish games like League of Legends. When he is not in front of a computer, he enjoys playing with his two kittens, hiking and kayaking. - - Yuzhi studied Computer Science in school. She liked the instant gratification of seeing code come to life without having to physically be in a laboratory. Now she’s a manager in the React org. Before management, she used to work on the Relay data fetching framework. In her spare time, Yuzhi enjoys optimizing her life via gardening and home improvement projects. diff --git a/src/content/community/versioning-policy.md b/src/content/community/versioning-policy.md index 7aa71efd2..a61d19942 100644 --- a/src/content/community/versioning-policy.md +++ b/src/content/community/versioning-policy.md @@ -8,7 +8,7 @@ All stable builds of React go through a high level of testing and follow semanti -For a list of previous releases, see the [Versions](/versions) page. +This versioning policy describes our approach to version numbers for packages such as `react` and `react-dom`. For a list of previous releases, see the [Versions](/versions) page. ## Stable releases {/*stable-releases*/} @@ -24,7 +24,9 @@ Major releases can also contain new features, and any release can include bug fi Minor releases are the most common type of release. -### Breaking Changes {/*breaking-changes*/} +We know our users continue to use old versions of React in production. If we learn of a security vulnerability in React, we release a backported fix for all major versions that are affected by the vulnerability. + +### Breaking changes {/*breaking-changes*/} Breaking changes are inconvenient for everyone, so we try to minimize the number of major releases – for example, React 15 was released in April 2016 and React 16 was released in September 2017, and React 17 was released in October 2020. diff --git a/src/content/learn/add-react-to-an-existing-project.md b/src/content/learn/add-react-to-an-existing-project.md index f494b0ab1..4684fb5b0 100644 --- a/src/content/learn/add-react-to-an-existing-project.md +++ b/src/content/learn/add-react-to-an-existing-project.md @@ -21,7 +21,7 @@ Let's say you have an existing web app at `example.com` built with another serve Here's how we recommend to set it up: 1. **Build the React part of your app** using one of the [React-based frameworks](/learn/start-a-new-react-project). -2. **Specify `/some-app` as the *base path*** in your framework's configuration (here's how: [Next.js](https://nextjs.org/docs/api-reference/next.config.js/basepath), [Gatsby](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/path-prefix/)). +2. **Specify `/some-app` as the *base path*** in your framework's configuration (here's how: [Next.js](https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath), [Gatsby](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/path-prefix/)). 3. **Configure your server or a proxy** so that all requests under `/some-app/` are handled by your React app. This ensures the React part of your app can [benefit from the best practices](/learn/start-a-new-react-project#can-i-use-react-without-a-framework) baked into those frameworks. @@ -45,7 +45,7 @@ A modular JavaScript environment lets you write your React components in individ * **If your app is already split into files that use `import` statements,** try to use the setup you already have. Check whether writing `
` in your JS code causes a syntax error. If it causes a syntax error, you might need to [transform your JavaScript code with Babel](https://babeljs.io/setup), and enable the [Babel React preset](https://babeljs.io/docs/babel-preset-react) to use JSX. -* **If your app doesn't have an existing setup for compiling JavaScript modules,** set it up with [Vite](https://vitejs.dev/). The Vite community maintains [many integrations with backend frameworks](https://github.com/vitejs/awesome-vite#integrations-with-backends), including Rails, Django, and Laravel. If your backend framework is not listed, [follow this guide](https://vitejs.dev/guide/backend-integration.html) to manually integrate Vite builds with your backend. +* **If your app doesn't have an existing setup for compiling JavaScript modules,** set it up with [Vite](https://vite.dev/). The Vite community maintains [many integrations with backend frameworks](https://github.com/vitejs/awesome-vite#integrations-with-backends), including Rails, Django, and Laravel. If your backend framework is not listed, [follow this guide](https://vite.dev/guide/backend-integration.html) to manually integrate Vite builds with your backend. To check whether your setup works, run this command in your project folder: @@ -57,12 +57,13 @@ Then add these lines of code at the top of your main JavaScript file (it might b -```html index.html hidden +```html public/index.html hidden My app +
``` @@ -84,7 +85,7 @@ If the entire content of your page was replaced by a "Hello, world!", everything -Integrating a modular JavaScript environment into an existing project for the first time can feel intimidating, but it's worth it! If you get stuck, try our [community resources](/community) or the [Vite Chat](https://chat.vitejs.dev/). +Integrating a modular JavaScript environment into an existing project for the first time can feel intimidating, but it's worth it! If you get stuck, try our [community resources](/community) or the [Vite Chat](https://chat.vite.dev/). @@ -119,7 +120,7 @@ This lets you find that HTML element with [`document.getElementById`](https://de -```html index.html +```html public/index.html My app diff --git a/src/content/learn/adding-interactivity.md b/src/content/learn/adding-interactivity.md index 0d4a3b23f..5c87a3e79 100644 --- a/src/content/learn/adding-interactivity.md +++ b/src/content/learn/adding-interactivity.md @@ -265,7 +265,7 @@ setCount(count + 1); // Request a re-render with 1 console.log(count); // Still 0! ``` -This behavior help you avoid subtle bugs. Here is a little chat app. Try to guess what happens if you press "Send" first and *then* change the recipient to Bob. Whose name will appear in the `alert` five seconds later? +This behavior helps you avoid subtle bugs. Here is a little chat app. Try to guess what happens if you press "Send" first and *then* change the recipient to Bob. Whose name will appear in the `alert` five seconds later? diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md new file mode 100644 index 000000000..b5f29e9af --- /dev/null +++ b/src/content/learn/build-a-react-app-from-scratch.md @@ -0,0 +1,143 @@ +--- +title: Build a React app from Scratch +--- + + + +If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can build a React app from scratch. + + + + + +#### Consider using a framework {/*consider-using-a-framework*/} + +Starting from scratch is an easy way to get started using React, but a major tradeoff to be aware of is that going this route is often the same as building your own adhoc framework. As your requirements evolve, you may need to solve more framework-like problems that our recommended frameworks already have well developed and supported solutions for. + +For example, if in the future your app needs support for server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC), you will have to implement those on your own. Similarly, future React features that require integrating at the framework level will have to be implemented on your own if you want to use them. + +Our recommended frameworks also help you build better performing apps. For example, reducing or eliminating waterfalls from network requests makes for a better user experience. This might not be a high priority when you are building a toy project, but if your app gains users you may want to improve its performance. + +Going this route also makes it more difficult to get support, since the way you develop routing, data-fetching, and other features will be unique to your situation. You should only choose this option if you are comfortable tackling these problems on your own, or if you’re confident that you will never need these features. + +For a list of recommended frameworks, check out [Creating a React App](/learn/creating-a-react-app). + + + + +## Step 1: Install a build tool {/*step-1-install-a-build-tool*/} + +The first step is to install a build tool like `vite`, `parcel`, or `rsbuild`. These build tools provide features to package and run source code, provide a development server for local development and a build command to deploy your app to a production server. + +### Vite {/*vite*/} + +[Vite](https://vite.dev/) is a build tool that aims to provide a faster and leaner development experience for modern web projects. + + +{`npm create vite@latest my-app -- --template react`} + + +Vite is opinionated and comes with sensible defaults out of the box. Vite has a rich ecosystem of plugins to support fast refresh, JSX, Babel/SWC, and other common features. See Vite's [React plugin](https://vite.dev/plugins/#vitejs-plugin-react) or [React SWC plugin](https://vite.dev/plugins/#vitejs-plugin-react-swc) and [React SSR example project](https://vite.dev/guide/ssr.html#example-projects) to get started. + +Vite is already being used as a build tool in one of our [recommended frameworks](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation). + +### Parcel {/*parcel*/} + +[Parcel](https://parceljs.org/) combines a great out-of-the-box development experience with a scalable architecture that can take your project from just getting started to massive production applications. + + +{`npm install --save-dev parcel`} + + +Parcel supports fast refresh, JSX, TypeScript, Flow, and styling out of the box. See [Parcel's React recipe](https://parceljs.org/recipes/react/#getting-started) to get started. + +### Rsbuild {/*rsbuild*/} + +[Rsbuild](https://rsbuild.dev/) is an Rspack-powered build tool that provides a seamless development experience for React applications. It comes with carefully tuned defaults and performance optimizations ready to use. + + +{`npx create-rsbuild --template react`} + + +Rsbuild includes built-in support for React features like fast refresh, JSX, TypeScript, and styling. See [Rsbuild's React guide](https://rsbuild.dev/guide/framework/react) to get started. + + + +#### Metro for React Native {/*react-native*/} + +If you're starting from scratch with React Native you'll need to use [Metro](https://metrobundler.dev/), the JavaScript bundler for React Native. Metro supports bundling for platforms like iOS and Android, but lacks many features when compared to the tools here. We recommend starting with Vite, Parcel, or Rsbuild unless your project requires React Native support. + + + +## Step 2: Build Common Application Patterns {/*step-2-build-common-application-patterns*/} + +The build tools listed above start off with a client-only, single-page app (SPA), but don't include any further solutions for common functionality like routing, data fetching, or styling. + +The React ecosystem includes many tools for these problems. We've listed a few that are widely used as a starting point, but feel free to choose other tools if those work better for you. + +### Routing {/*routing*/} + +Routing determines what content or pages to display when a user visits a particular URL. You need to set up a router to map URLs to different parts of your app. You'll also need to handle nested routes, route parameters, and query parameters. Routers can be configured within your code, or defined based on your component folder and file structures. + +Routers are a core part of modern applications, and are usually integrated with data fetching (including prefetching data for a whole page for faster loading), code splitting (to minimize client bundle sizes), and page rendering approaches (to decide how each page gets generated). + +We suggest using: + +- [React Router](https://reactrouter.com/start/data/custom) +- [Tanstack Router](https://tanstack.com/router/latest) + + +### Data Fetching {/*data-fetching*/} + +Fetching data from a server or other data source is a key part of most applications. Doing this properly requires handling loading states, error states, and caching the fetched data, which can be complex. + +Purpose-built data fetching libraries do the hard work of fetching and caching the data for you, letting you focus on what data your app needs and how to display it. These libraries are typically used directly in your components, but can also be integrated into routing loaders for faster pre-fetching and better performance, and in server rendering as well. + +Note that fetching data directly in components can lead to slower loading times due to network request waterfalls, so we recommend prefetching data in router loaders or on the server as much as possible! This allows a page's data to be fetched all at once as the page is being displayed. + +If you're fetching data from most backends or REST-style APIs, we suggest using: + +- [React Query](https://react-query.tanstack.com/) +- [SWR](https://swr.vercel.app/) +- [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) + +If you're fetching data from a GraphQL API, we suggest using: + +- [Apollo](https://www.apollographql.com/docs/react) +- [Relay](https://relay.dev/) + + +### Code-splitting {/*code-splitting*/} + +Code-splitting is the process of breaking your app into smaller bundles that can be loaded on demand. An app's code size increases with every new feature and additional dependency. Apps can become slow to load because all of the code for the entire app needs to be sent before it can be used. Caching, reducing features/dependencies, and moving some code to run on the server can help mitigate slow loading but are incomplete solutions that can sacrifice functionality if overused. + +Similarly, if you rely on the apps using your framework to split the code, you might encounter situations where loading becomes slower than if no code splitting were happening at all. For example, [lazily loading](/reference/react/lazy) a chart delays sending the code needed to render the chart, splitting the chart code from the rest of the app. [Parcel supports code splitting with React.lazy](https://parceljs.org/recipes/react/#code-splitting). However, if the chart loads its data *after* it has been initially rendered you are now waiting twice. This is a waterfall: rather than fetching the data for the chart and sending the code to render it simultaneously, you must wait for each step to complete one after the other. + +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://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) + +### Improving Application Performance {/*improving-application-performance*/} + +Since the build tool you select only support single page apps (SPAs) you'll need to implement other [rendering patterns](https://www.patterns.dev/vanilla/rendering-patterns) like server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC). Even if you don't need these features at first, in the future there may be some routes that would benefit SSR, SSG or RSC. + +* **Single-page apps (SPA)** load a single HTML page and dynamically updates the page as the user interacts with the app. SPAs are easier to get started with, but they can have slower initial load times. SPAs are the default architecture for most build tools. + +* **Streaming Server-side rendering (SSR)** renders a page on the server and sends the fully rendered page to the client. SSR can improve performance, but it can be more complex to set up and maintain than a single-page app. With the addition of streaming, SSR can be very complex to set up and maintain. See [Vite's SSR guide]( https://vite.dev/guide/ssr). + +* **Static site generation (SSG)** generates static HTML files for your app at build time. SSG can improve performance, but it can be more complex to set up and maintain than server-side rendering. See [Vite's SSG guide](https://vite.dev/guide/ssr.html#pre-rendering-ssg). + +* **React Server Components (RSC)** lets you mix build-time, server-only, and interactive components in a single React tree. RSC can improve performance, but it currently requires deep expertise to set up and maintain. See [Parcel's RSC examples](https://github.com/parcel-bundler/rsc-examples). + +Your rendering strategies need to integrate with your router so apps built with your framework can choose the rendering strategy on a per-route level. This will enable different rendering strategies without having to rewrite your whole app. For example, the landing page for your app might benefit from being statically generated (SSG), while a page with a content feed might perform best with server-side rendering. + +Using the right rendering strategy for the right routes can decrease the time it takes for the first byte of content to be loaded ([Time to First Byte](https://web.dev/articles/ttfb)), the first piece of content to render ([First Contentful Paint](https://web.dev/articles/fcp)), and the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)). + +### And more... {/*and-more*/} + +These are just a few examples of the features a new app will need to consider when building from scratch. Many limitations you'll hit can be difficult to solve as each problem is interconnected with the others and can require deep expertise in problem areas you may not be familiar with. + +If you don't want to solve these problems on your own, you can [get started with a framework](/learn/creating-a-react-app) that provides these features out of the box. diff --git a/src/content/learn/conditional-rendering.md b/src/content/learn/conditional-rendering.md index 895d610d3..95be5d2e0 100644 --- a/src/content/learn/conditional-rendering.md +++ b/src/content/learn/conditional-rendering.md @@ -52,13 +52,13 @@ export default function PackingList() { -Notice that some of the `Item` components have their `isPacked` prop set to `true` instead of `false`. You want to add a checkmark (✔) to packed items if `isPacked={true}`. +Notice that some of the `Item` components have their `isPacked` prop set to `true` instead of `false`. You want to add a checkmark (✅) to packed items if `isPacked={true}`. You can write this as an [`if`/`else` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) like so: ```js if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; ``` @@ -70,7 +70,7 @@ If the `isPacked` prop is `true`, this code **returns a different JSX tree.** Wi ```js function Item({ name, isPacked }) { if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; } @@ -159,7 +159,7 @@ In practice, returning `null` from a component isn't common because it might sur In the previous example, you controlled which (if any!) JSX tree would be returned by the component. You may already have noticed some duplication in the render output: ```js -
  • {name} ✔
  • +
  • {name} ✅
  • ``` is very similar to @@ -172,7 +172,7 @@ Both of the conditional branches return `
  • ...
  • `: ```js if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; ``` @@ -187,7 +187,7 @@ Instead of this: ```js if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; ``` @@ -197,12 +197,12 @@ You can write this: ```js return (
  • - {isPacked ? name + ' ✔' : name} + {isPacked ? name + ' ✅' : name}
  • ); ``` -You can read it as *"if `isPacked` is true, then (`?`) render `name + ' ✔'`, otherwise (`:`) render `name`"*. +You can read it as *"if `isPacked` is true, then (`?`) render `name + ' ✅'`, otherwise (`:`) render `name`"*. @@ -222,7 +222,7 @@ function Item({ name, isPacked }) {
  • {isPacked ? ( - {name + ' ✔'} + {name + ' ✅'} ) : ( name @@ -265,7 +265,7 @@ Another common shortcut you'll encounter is the [JavaScript logical AND (`&&`) o ```js return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); ``` @@ -280,7 +280,7 @@ Here it is in action: function Item({ name, isPacked }) { return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); } @@ -337,7 +337,7 @@ Use an `if` statement to reassign a JSX expression to `itemContent` if `isPacked ```js if (isPacked) { - itemContent = name + " ✔"; + itemContent = name + " ✅"; } ``` @@ -357,7 +357,7 @@ This style is the most verbose, but it's also the most flexible. Here it is in a function Item({ name, isPacked }) { let itemContent = name; if (isPacked) { - itemContent = name + " ✔"; + itemContent = name + " ✅"; } return (
  • @@ -401,7 +401,7 @@ function Item({ name, isPacked }) { if (isPacked) { itemContent = ( - {name + " ✔"} + {name + " ✅"} ); } @@ -464,7 +464,7 @@ Use the conditional operator (`cond ? a : b`) to render a ❌ if `isPacked` isn function Item({ name, isPacked }) { return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); } @@ -502,7 +502,7 @@ export default function PackingList() { function Item({ name, isPacked }) { return (
  • - {name} {isPacked ? '✔' : '❌'} + {name} {isPacked ? '✅' : '❌'}
  • ); } diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md new file mode 100644 index 000000000..df512cca8 --- /dev/null +++ b/src/content/learn/creating-a-react-app.md @@ -0,0 +1,113 @@ +--- +title: Creating a React App +--- + + + +If you want to build a new app or website with React, we recommend starting with a framework. + + + +If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can [build a React app from scratch](/learn/build-a-react-app-from-scratch). + +## Full-stack frameworks {/*full-stack-frameworks*/} + +These recommended frameworks support all the features you need to deploy and scale your app in production. They have integrated the latest React features and take advantage of React’s architecture. + + + +#### Full-stack frameworks do not require a server. {/*react-frameworks-do-not-require-a-server*/} + +All the frameworks on this page support client-side rendering ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), single-page apps ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), and static-site generation ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). These apps can be deployed to a [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) or static hosting service without a server. Additionally, these frameworks allow you to add server-side rendering on a per-route basis, when it makes sense for your use case. + +This allows you to start with a client-only app, and if your needs change later, you can opt-in to using server features on individual routes without rewriting your app. See your framework's documentation for configuring the rendering strategy. + + + +### Next.js (App Router) {/*nextjs-app-router*/} + +**[Next.js's App Router](https://nextjs.org/docs) is a React framework that takes full advantage of React's architecture to enable full-stack React apps.** + + +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 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*/} + +**[React Router](https://reactrouter.com/start/framework/installation) is the most popular routing library for React and can be paired with Vite to create a full-stack React framework**. It emphasizes standard Web APIs and has several [ready to deploy templates](https://github.com/remix-run/react-router-templates) for various JavaScript runtimes and platforms. + +To create a new React Router framework project, run: + + +npx create-react-router@latest + + +React Router is maintained by [Shopify](https://www.shopify.com). + +### Expo (for native apps) {/*expo*/} + +**[Expo](https://expo.dev/) is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs.** It provides an SDK for [React Native](https://reactnative.dev/) that makes the native parts easier to use. To create a new Expo project, run: + + +npx create-expo-app@latest + + +If you're new to Expo, check out the [Expo tutorial](https://docs.expo.dev/tutorial/introduction/). + +Expo is maintained by [Expo (the company)](https://expo.dev/about). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services. + + +## Other frameworks {/*other-frameworks*/} + +There are other up-and-coming frameworks that are working towards our full stack React vision: + +- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more using tools like Nitro and Vite. +- [RedwoodJS](https://redwoodjs.com/): Redwood is a full stack React framework with lots of pre-installed packages and configuration that makes it easy to build full-stack web applications. + + + +#### Which features make up the React team’s full-stack architecture vision? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/} + +Next.js's App Router bundler fully implements the official [React Server Components specification](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). This lets you mix build-time, server-only, and interactive components in a single React tree. + +For example, you can write a server-only React component as an `async` function that reads from a database or from a file. Then you can pass data down from it to your interactive components: + +```js +// This component runs *only* on the server (or during the build). +async function Talks({ confId }) { + // 1. You're on the server, so you can talk to your data layer. API endpoint not required. + const talks = await db.Talks.findAll({ confId }); + + // 2. Add any amount of rendering logic. It won't make your JavaScript bundle larger. + const videos = talks.map(talk => talk.video); + + // 3. Pass the data down to the components that will run in the browser. + return ; +} +``` + +Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). This lets you specify a loading state (like a skeleton placeholder) for different parts of your user interface directly in your React tree: + +```js +}> + + +``` + +Server Components and Suspense are React features rather than Next.js features. However, adopting them at the framework level requires buy-in and non-trivial implementation work. At the moment, the Next.js App Router is the most complete implementation. The React team is working with bundler developers to make these features easier to implement in the next generation of frameworks. + + + +## Start From Scratch {/*start-from-scratch*/} + +If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, there are other options available for starting a React project from scratch. + +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](#full-stack-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 build tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/). + +----- + +_If you’re a framework author interested in being included on this page, [please let us know](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._ diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index ce49b85c8..34ee0c01a 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -327,7 +327,7 @@ In this example, the JavaScript `&&` operator is used to conditionally render a function Item({ name, isPacked }) { return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); } diff --git a/src/content/learn/index.md b/src/content/learn/index.md index b57655bc4..15e3b2866 100644 --- a/src/content/learn/index.md +++ b/src/content/learn/index.md @@ -4,7 +4,7 @@ title: Quick Start -Welcome to the React documentation! This page will give you an introduction to the 80% of React concepts that you will use on a daily basis. +Welcome to the React documentation! This page will give you an introduction to 80% of the React concepts that you will use on a daily basis. diff --git a/src/content/learn/installation.md b/src/content/learn/installation.md index c5426ea94..ab538e5bb 100644 --- a/src/content/learn/installation.md +++ b/src/content/learn/installation.md @@ -8,15 +8,6 @@ React has been designed from the start for gradual adoption. You can use as litt - - -* [How to start a new React project](/learn/start-a-new-react-project) -* [How to add React to an existing project](/learn/add-react-to-an-existing-project) -* [How to set up your editor](/learn/editor-setup) -* [How to install React Developer Tools](/learn/react-developer-tools) - - - ## Try React {/*try-react*/} You don't need to install anything to play with React. Try editing this sandbox! @@ -37,19 +28,30 @@ export default function App() { You can edit it directly or open it in a new tab by pressing the "Fork" button in the upper right corner. -Most pages in the React documentation contain sandboxes like this. Outside of the React documentation, there are many online sandboxes that support React: for example, [CodeSandbox](https://codesandbox.io/s/new), [StackBlitz](https://stackblitz.com/fork/react), or [CodePen.](https://codepen.io/pen?&editors=0010&layout=left&prefill_data_id=3f4569d1-1b11-4bce-bd46-89090eed5ddb) - -### Try React locally {/*try-react-locally*/} +Most pages in the React documentation contain sandboxes like this. Outside of the React documentation, there are many online sandboxes that support React: for example, [CodeSandbox](https://codesandbox.io/s/new), [StackBlitz](https://stackblitz.com/fork/react), or [CodePen.](https://codepen.io/pen?template=QWYVwWN) To try React locally on your computer, [download this HTML page.](https://gist.githubusercontent.com/gaearon/0275b1e1518599bbeafcde4722e79ed1/raw/db72dcbf3384ee1708c4a07d3be79860db04bff0/example.html) Open it in your editor and in your browser! -## Start a new React project {/*start-a-new-react-project*/} +## Creating a React App {/*creating-a-react-app*/} + +If you want to start a new React app, you can [create a React app](/learn/creating-a-react-app) using a recommended framework. + +## Build a React App from Scratch {/*build-a-react-app-from-scratch*/} -If you want to build an app or a website fully with React, [start a new React project.](/learn/start-a-new-react-project) +If a framework is not a good fit for your project, you prefer to build your own framework, or you just want to learn the basics of a React app you can [build a React app from scratch](/learn/build-a-react-app-from-scratch). ## Add React to an existing project {/*add-react-to-an-existing-project*/} -If want to try using React in your existing app or a website, [add React to an existing project.](/learn/add-react-to-an-existing-project) +If want to try using React in your existing app or a website, you can [add React to an existing project.](/learn/add-react-to-an-existing-project) + + + + +#### Should I use Create React App? {/*should-i-use-create-react-app*/} + +No. Create React App has been deprecated. For more information, see [Sunsetting Create React App](/blog/2025/02/14/sunsetting-create-react-app). + + ## Next steps {/*next-steps*/} diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 2d44d7353..2053f936b 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -124,35 +124,35 @@ export default function CatFriends() { <>
    • Tom
    • Maru
    • Jellylorum
    • @@ -245,9 +245,9 @@ export default function CatFriends() { return ( <>
        @@ -256,11 +256,11 @@ export default function CatFriends() { key={cat} ref={(node) => { const map = getMap(); - if (node) { - map.set(cat, node); - } else { + map.set(cat, node); + + return () => { map.delete(cat); - } + }; }} > @@ -309,42 +309,10 @@ li { } ``` -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0" - } -} -``` - In this example, `itemsRef` doesn't hold a single DOM node. Instead, it holds a [Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) from item ID to a DOM node. ([Refs can hold any values!](/learn/referencing-values-with-refs)) The [`ref` callback](/reference/react-dom/components/common#ref-callback) on every list item takes care to update the Map: -```js -
      • { - const map = getMap(); - if (node) { - // Add to the Map - map.set(cat, node); - } else { - // Remove from the Map - map.delete(cat); - } - }} -> -``` - -This lets you read individual DOM nodes from the Map later. - - - -This example shows another approach for managing the Map with a `ref` callback cleanup function. - ```js
      • ``` - +This lets you read individual DOM nodes from the Map later. + + + +When Strict Mode is enabled, ref callbacks will run twice in development. + +Read more about [how this helps find bugs](/reference/react/StrictMode#fixing-bugs-found-by-re-running-ref-callbacks-in-development) in callback refs. + + ## Accessing another component's DOM nodes {/*accessing-another-components-dom-nodes*/} -When you put a ref on a built-in component that outputs a browser element like ``, React will set that ref's `current` property to the corresponding DOM node (such as the actual `` in the browser). + +Refs are an escape hatch. Manually manipulating _another_ component's DOM nodes can make your code fragile. + -However, if you try to put a ref on **your own** component, like ``, by default you will get `null`. Here is an example demonstrating it. Notice how clicking the button **does not** focus the input: - - +You can pass refs from parent component to child components [just like any other prop](/learn/passing-props-to-a-component). -```js +```js {3-4,9} import { useRef } from 'react'; -function MyInput(props) { - return ; +function MyInput({ ref }) { + return ; } -export default function MyForm() { +function MyForm() { const inputRef = useRef(null); - - function handleClick() { - inputRef.current.focus(); - } - - return ( - <> - - - - ); + return } ``` - - -To help you notice the issue, React also prints an error to the console: - - - -Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? - - - -This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating _another_ component's DOM nodes makes your code even more fragile. - -Instead, components that _want_ to expose their DOM nodes have to **opt in** to that behavior. A component can specify that it "forwards" its ref to one of its children. Here's how `MyInput` can use the `forwardRef` API: - -```js -const MyInput = forwardRef((props, ref) => { - return ; -}); -``` - -This is how it works: - -1. `` tells React to put the corresponding DOM node into `inputRef.current`. However, it's up to the `MyInput` component to opt into that--by default, it doesn't. -2. The `MyInput` component is declared using `forwardRef`. **This opts it into receiving the `inputRef` from above as the second `ref` argument** which is declared after `props`. -3. `MyInput` itself passes the `ref` it received to the `` inside of it. +In the above example, a ref is created in the parent component, `MyForm`, and is passed to the child component, `MyInput`. `MyInput` then passes the ref to ``. Because `` is a [built-in component](/reference/react-dom/components/common) React sets the `.current` property of the ref to the `` DOM element. -Now clicking the button to focus the input works: +The `inputRef` created in `MyForm` now points to the `` DOM element returned by `MyInput`. A click handler created in `MyForm` can access `inputRef` and call `focus()` to set the focus on ``. ```js -import { forwardRef, useRef } from 'react'; +import { useRef } from 'react'; -const MyInput = forwardRef((props, ref) => { - return ; -}); +function MyInput({ ref }) { + return ; +} -export default function Form() { +export default function MyForm() { const inputRef = useRef(null); function handleClick() { @@ -455,24 +395,18 @@ export default function Form() { -In design systems, it is a common pattern for low-level components like buttons, inputs, and so on, to forward their refs to their DOM nodes. On the other hand, high-level components like forms, lists, or page sections usually won't expose their DOM nodes to avoid accidental dependencies on the DOM structure. - #### Exposing a subset of the API with an imperative handle {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} -In the above example, `MyInput` exposes the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with `useImperativeHandle`: +In the above example, the ref passed to `MyInput` is passed on to the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with [`useImperativeHandle`](/reference/react/useImperativeHandle): ```js -import { - forwardRef, - useRef, - useImperativeHandle -} from 'react'; +import { useRef, useImperativeHandle } from "react"; -const MyInput = forwardRef((props, ref) => { +function MyInput({ ref }) { const realInputRef = useRef(null); useImperativeHandle(ref, () => ({ // Only expose focus and nothing else @@ -480,8 +414,8 @@ const MyInput = forwardRef((props, ref) => { realInputRef.current.focus(); }, })); - return ; -}); + return ; +}; export default function Form() { const inputRef = useRef(null); @@ -493,9 +427,7 @@ export default function Form() { return ( <> - + ); } @@ -503,7 +435,7 @@ export default function Form() { -Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, `useImperativeHandle` instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside `useImperativeHandle` call. +Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, [`useImperativeHandle`](/reference/react/useImperativeHandle) instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside [`useImperativeHandle`](/reference/react/useImperativeHandle) call. @@ -615,7 +547,7 @@ export default function TodoList() { const newTodo = { id: nextId++, text: text }; flushSync(() => { setText(''); - setTodos([ ...todos, newTodo]); + setTodos([ ...todos, newTodo]); }); listRef.current.lastChild.scrollIntoView({ behavior: 'smooth', @@ -715,7 +647,7 @@ However, this doesn't mean that you can't do it at all. It requires caution. **Y - Refs are a generic concept, but most often you'll use them to hold DOM elements. - You instruct React to put a DOM node into `myRef.current` by passing `
        `. - Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements. -- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using `forwardRef` and passing the second `ref` argument down to a specific node. +- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using the `ref` prop. - Avoid changing DOM nodes managed by React. - If you do modify DOM nodes managed by React, modify parts that React has no reason to update. @@ -948,7 +880,7 @@ const catList = []; for (let i = 0; i < 10; i++) { catList.push({ id: i, - imageUrl: 'https://placekitten.com/250/200?image=' + i + imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i }); } @@ -1065,7 +997,7 @@ const catList = []; for (let i = 0; i < 10; i++) { catList.push({ id: i, - imageUrl: 'https://placekitten.com/250/200?image=' + i + imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i }); } @@ -1117,7 +1049,7 @@ Make it so that clicking the "Search" button puts focus into the field. Note tha -You'll need `forwardRef` to opt into exposing a DOM node from your own component like `SearchInput`. +You'll need to pass `ref` as a prop to opt into exposing a DOM node from your own component like `SearchInput`. @@ -1202,18 +1134,14 @@ export default function SearchButton({ onClick }) { ``` ```js src/SearchInput.js -import { forwardRef } from 'react'; - -export default forwardRef( - function SearchInput(props, ref) { - return ( - - ); - } -); +export default function SearchInput({ ref }) { + return ( + + ); +} ``` ```css diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md index 1aea87b35..e81678c8e 100644 --- a/src/content/learn/passing-data-deeply-with-context.md +++ b/src/content/learn/passing-data-deeply-with-context.md @@ -468,15 +468,15 @@ import { LevelContext } from './LevelContext.js'; export default function Section({ level, children }) { return (
        - + {children} - +
        ); } ``` -This tells React: "if any component inside this `
        ` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it. +This tells React: "if any component inside this `
        ` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it. @@ -514,9 +514,9 @@ import { LevelContext } from './LevelContext.js'; export default function Section({ level, children }) { return (
        - + {children} - +
        ); } @@ -567,7 +567,7 @@ export const LevelContext = createContext(1); It's the same result as the original code, but you did not need to pass the `level` prop to each `Heading` component! Instead, it "figures out" its heading level by asking the closest `Section` above: 1. You pass a `level` prop to the `
        `. -2. `Section` wraps its children into ``. +2. `Section` wraps its children into ``. 3. `Heading` asks the closest value of `LevelContext` above with `useContext(LevelContext)`. ## Using and providing context from the same component {/*using-and-providing-context-from-the-same-component*/} @@ -595,9 +595,9 @@ export default function Section({ children }) { const level = useContext(LevelContext); return (
        - + {children} - +
        ); } @@ -643,9 +643,9 @@ export default function Section({ children }) { const level = useContext(LevelContext); return (
        - + {children} - +
        ); } @@ -776,9 +776,9 @@ export default function Section({ children, isFancy }) { 'section ' + (isFancy ? 'fancy' : '') }> - + {children} - +
        ); } @@ -868,7 +868,7 @@ In general, if some information is needed by distant components in different par * To pass context: 1. Create and export it with `export const MyContext = createContext(defaultValue)`. 2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep. - 3. Wrap children into `` to provide it from a parent. + 3. Wrap children into `` to provide it from a parent. * Context passes through any components in the middle. * Context lets you write components that "adapt to their surroundings". * Before you use context, try passing props or passing JSX as `children`. @@ -1022,7 +1022,7 @@ li { Remove `imageSize` prop from all the components. -Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`: +Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`: @@ -1036,7 +1036,7 @@ export default function App() { const [isLarge, setIsLarge] = useState(false); const imageSize = isLarge ? 150 : 100; return ( -
        -
        +
        ) } diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md index d35071845..bf5531f35 100644 --- a/src/content/learn/preserving-and-resetting-state.md +++ b/src/content/learn/preserving-and-resetting-state.md @@ -2011,7 +2011,7 @@ export default function ContactList() {
        -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/render-and-commit.md b/src/content/learn/render-and-commit.md index 3f0593599..f9b05e185 100644 --- a/src/content/learn/render-and-commit.md +++ b/src/content/learn/render-and-commit.md @@ -70,7 +70,7 @@ Try commenting out the `root.render()` call and see the component disappear! Once the component has been initially rendered, you can trigger further renders by updating its state with the [`set` function.](/reference/react/useState#setstate) Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.) - + @@ -84,7 +84,7 @@ After you trigger a render, React calls your components to figure out what to di This process is recursive: if the updated component returns some other component, React will render _that_ component next, and if that component also returns something, it will render _that_ component next, and so on. The process will continue until there are no more nested components and React knows exactly what should be displayed on screen. -In the following example, React will call `Gallery()` and `Image()` several times: +In the following example, React will call `Gallery()` and `Image()` several times: @@ -148,9 +148,9 @@ The default behavior of rendering all components nested within the updated compo ## Step 3: React commits changes to the DOM {/*step-3-react-commits-changes-to-the-dom*/} -After rendering (calling) your components, React will modify the DOM. +After rendering (calling) your components, React will modify the DOM. -* **For the initial render,** React will use the [`appendChild()`](https://developer.mozilla.org/docs/Web/API/Node/appendChild) DOM API to put all the DOM nodes it has created on screen. +* **For the initial render,** React will use the [`appendChild()`](https://developer.mozilla.org/docs/Web/API/Node/appendChild) DOM API to put all the DOM nodes it has created on screen. * **For re-renders,** React will apply the minimal necessary operations (calculated while rendering!) to make the DOM match the latest rendering output. **React only changes the DOM nodes if there's a difference between renders.** For example, here is a component that re-renders with different props passed from its parent every second. Notice how you can add some text into the ``, updating its `value`, but the text doesn't disappear when the component re-renders: diff --git a/src/content/learn/reusing-logic-with-custom-hooks.md b/src/content/learn/reusing-logic-with-custom-hooks.md index 13a556c7b..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 }) { @@ -1333,7 +1333,7 @@ export function useOnlineStatus() { In the above example, `useOnlineStatus` is implemented with a pair of [`useState`](/reference/react/useState) and [`useEffect`.](/reference/react/useEffect) However, this isn't the best possible solution. There is a number of edge cases it doesn't consider. For example, it assumes that when the component mounts, `isOnline` is already `true`, but this may be wrong if the network already went offline. You can use the browser [`navigator.onLine`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) API to check for that, but using it directly would not work on the server for generating the initial HTML. In short, this code could be improved. -Luckily, React 18 includes a dedicated API called [`useSyncExternalStore`](/reference/react/useSyncExternalStore) which takes care of all of these problems for you. Here is how your `useOnlineStatus` Hook, rewritten to take advantage of this new API: +React includes a dedicated API called [`useSyncExternalStore`](/reference/react/useSyncExternalStore) which takes care of all of these problems for you. Here is your `useOnlineStatus` Hook, rewritten to take advantage of this new API: @@ -1899,7 +1899,7 @@ export default function Counter() { } ``` -You'll need to write your custom Hook in `useCounter.js` and import it into the `Counter.js` file. +You'll need to write your custom Hook in `useCounter.js` and import it into the `App.js` file. @@ -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/separating-events-from-effects.md b/src/content/learn/separating-events-from-effects.md index 21276c287..335867b4d 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: diff --git a/src/content/learn/setup.md b/src/content/learn/setup.md new file mode 100644 index 000000000..2c46ee148 --- /dev/null +++ b/src/content/learn/setup.md @@ -0,0 +1,28 @@ +--- +title: Setup +--- + + +React integrates with tools like editors, TypeScript, browser extensions, and compilers. This section will help you get your environment set up. + + + +## Editor Setup {/*editor-setup*/} + +See our [recommended editors](/learn/editor-setup) and learn how to set them up to work with React. + +## Using TypeScript {/*using-typescript*/} + +TypeScript is a popular way to add type definitions to JavaScript codebases. [Learn how to integrate TypeScript into your React projects](/learn/typescript). + +## React Developer Tools {/*react-developer-tools*/} + +React Developer Tools is a browser extension that can inspect React components, edit props and state, and identify performance problems. Learn how to install it [here](learn/react-developer-tools). + +## React Compiler {/*react-compiler*/} + +React Compiler is a tool that automatically optimizes your React app. [Learn more](/learn/react-compiler). + +## Next steps {/*next-steps*/} + +Head to the [Quick Start](/learn) guide for a tour of the most important React concepts you will encounter every day. diff --git a/src/content/learn/start-a-new-react-project.md b/src/content/learn/start-a-new-react-project.md deleted file mode 100644 index bd5ba6c50..000000000 --- a/src/content/learn/start-a-new-react-project.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Start a New React Project ---- - - - -If you want to build a new app or a new website fully with React, we recommend picking one of the React-powered frameworks popular in the community. - - - - -You can use React without a framework, however we’ve found that most apps and sites eventually build solutions to common problems such as code-splitting, routing, data fetching, and generating HTML. These problems are common to all UI libraries, not just React. - -By starting with a framework, you can get started with React quickly, and avoid essentially building your own framework later. - - - -#### Can I use React without a framework? {/*can-i-use-react-without-a-framework*/} - -You can definitely use React without a framework--that's how you'd [use React for a part of your page.](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page) **However, if you're building a new app or a site fully with React, we recommend using a framework.** - -Here's why. - -Even if you don't need routing or data fetching at first, you'll likely want to add some libraries for them. As your JavaScript bundle grows with every new feature, you might have to figure out how to split code for every route individually. As your data fetching needs get more complex, you are likely to encounter server-client network waterfalls that make your app feel very slow. As your audience includes more users with poor network conditions and low-end devices, you might need to generate HTML from your components to display content early--either on the server, or during the build time. Changing your setup to run some of your code on the server or during the build can be very tricky. - -**These problems are not React-specific. This is why Svelte has SvelteKit, Vue has Nuxt, and so on.** To solve these problems on your own, you'll need to integrate your bundler with your router and with your data fetching library. It's not hard to get an initial setup working, but there are a lot of subtleties involved in making an app that loads quickly even as it grows over time. You'll want to send down the minimal amount of app code but do so in a single client–server roundtrip, in parallel with any data required for the page. You'll likely want the page to be interactive before your JavaScript code even runs, to support progressive enhancement. You may want to generate a folder of fully static HTML files for your marketing pages that can be hosted anywhere and still work with JavaScript disabled. Building these capabilities yourself takes real work. - -**React frameworks on this page solve problems like these by default, with no extra work from your side.** They let you start very lean and then scale your app with your needs. Each React framework has a community, so finding answers to questions and upgrading tooling is easier. Frameworks also give structure to your code, helping you and others retain context and skills between different projects. Conversely, with a custom setup it's easier to get stuck on unsupported dependency versions, and you'll essentially end up creating your own framework—albeit one with no community or upgrade path (and if it's anything like the ones we've made in the past, more haphazardly designed). - -If your app has unusual constraints not served well by these frameworks, or you prefer to solve these problems yourself, you can roll your own custom setup with React. Grab `react` and `react-dom` from npm, set up your custom build process with a bundler like [Vite](https://vitejs.dev/) or [Parcel](https://parceljs.org/), and add other tools as you need them for routing, static generation or server-side rendering, and more. - - - -## Production-grade React frameworks {/*production-grade-react-frameworks*/} - -These frameworks support all the features you need to deploy and scale your app in production and are working towards supporting our [full-stack architecture vision](#which-features-make-up-the-react-teams-full-stack-architecture-vision). All of the frameworks we recommend are open source with active communities for support, and can be deployed to your own server or a hosting provider. If you’re a framework author interested in being included on this list, [please let us know](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+). - -### Next.js {/*nextjs-pages-router*/} - -**[Next.js' Pages Router](https://nextjs.org/) is a full-stack React framework.** It's versatile and lets you create React apps of any size--from a mostly static blog to a complex dynamic application. To create a new Next.js project, run in your terminal: - - -npx create-next-app@latest - - -If you're new to Next.js, check out the [learn Next.js course.](https://nextjs.org/learn) - -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 a [static export](https://nextjs.org/docs/pages/building-your-application/deploying/static-exports) which doesn't require a server. - -### Remix {/*remix*/} - -**[Remix](https://remix.run/) is a full-stack React framework with nested routing.** It lets you break your app into nested parts that can load data in parallel and refresh in response to the user actions. To create a new Remix project, run: - - -npx create-remix - - -If you're new to Remix, check out the Remix [blog tutorial](https://remix.run/docs/en/main/tutorials/blog) (short) and [app tutorial](https://remix.run/docs/en/main/tutorials/jokes) (long). - -Remix is maintained by [Shopify](https://www.shopify.com/). When you create a Remix project, you need to [pick your deployment target](https://remix.run/docs/en/main/guides/deployment). You can deploy a Remix app to any Node.js or serverless hosting by using or writing an [adapter](https://remix.run/docs/en/main/other-api/adapter). - -### Gatsby {/*gatsby*/} - -**[Gatsby](https://www.gatsbyjs.com/) is a React framework for fast CMS-backed websites.** Its rich plugin ecosystem and its GraphQL data layer simplify integrating content, APIs, and services into one website. To create a new Gatsby project, run: - - -npx create-gatsby - - -If you're new to Gatsby, check out the [Gatsby tutorial.](https://www.gatsbyjs.com/docs/tutorial/) - -Gatsby is maintained by [Netlify](https://www.netlify.com/). You can [deploy a fully static Gatsby site](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting) to any static hosting. If you opt into using server-only features, make sure your hosting provider supports them for Gatsby. - -### Expo (for native apps) {/*expo*/} - -**[Expo](https://expo.dev/) is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs.** It provides an SDK for [React Native](https://reactnative.dev/) that makes the native parts easier to use. To create a new Expo project, run: - - -npx create-expo-app - - -If you're new to Expo, check out the [Expo tutorial](https://docs.expo.dev/tutorial/introduction/). - -Expo is maintained by [Expo (the company)](https://expo.dev/about). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services. - -## Bleeding-edge React frameworks {/*bleeding-edge-react-frameworks*/} - -As we've explored how to continue improving React, we realized that integrating React more closely with frameworks (specifically, with routing, bundling, and server technologies) is our biggest opportunity to help React users build better apps. The Next.js team has agreed to collaborate with us in researching, developing, integrating, and testing framework-agnostic bleeding-edge React features like [React Server Components.](/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components) - -These features are getting closer to being production-ready every day, and we've been in talks with other bundler and framework developers about integrating them. Our hope is that in a year or two, all frameworks listed on this page will have full support for these features. (If you're a framework author interested in partnering with us to experiment with these features, please let us know!) - -### Next.js (App Router) {/*nextjs-app-router*/} - -**[Next.js's App Router](https://nextjs.org/docs) is a redesign of the Next.js APIs aiming to fulfill the React team’s full-stack architecture vision.** It lets you fetch data in asynchronous components that run on the server or even during the build. - -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. - - - -#### Which features make up the React team’s full-stack architecture vision? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/} - -Next.js's App Router bundler fully implements the official [React Server Components specification](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). This lets you mix build-time, server-only, and interactive components in a single React tree. - -For example, you can write a server-only React component as an `async` function that reads from a database or from a file. Then you can pass data down from it to your interactive components: - -```js -// This component runs *only* on the server (or during the build). -async function Talks({ confId }) { - // 1. You're on the server, so you can talk to your data layer. API endpoint not required. - const talks = await db.Talks.findAll({ confId }); - - // 2. Add any amount of rendering logic. It won't make your JavaScript bundle larger. - const videos = talks.map(talk => talk.video); - - // 3. Pass the data down to the components that will run in the browser. - return ; -} -``` - -Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). This lets you specify a loading state (like a skeleton placeholder) for different parts of your user interface directly in your React tree: - -```js -}> - - -``` - -Server Components and Suspense are React features rather than Next.js features. However, adopting them at the framework level requires buy-in and non-trivial implementation work. At the moment, the Next.js App Router is the most complete implementation. The React team is working with bundler developers to make these features easier to implement in the next generation of frameworks. - - diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md index 75a1fd0b9..73d46bdab 100644 --- a/src/content/learn/state-a-components-memory.md +++ b/src/content/learn/state-a-components-memory.md @@ -1452,7 +1452,7 @@ If your linter is [configured for React](/learn/editor-setup#linting), you shoul #### Remove unnecessary state {/*remove-unnecessary-state*/} -When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason it always shows "Hello, !". +When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason the first time it shows "Hello, !", and then "Hello, [name]!" with the previous input every time after. To fix this code, remove the unnecessary state variable. (We will discuss about [why this didn't work](/learn/state-as-a-snapshot) later.) diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 9ca109656..115075161 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -627,7 +627,7 @@ See the examples below for how to handle common patterns. ### Controlling non-React widgets {/*controlling-non-react-widgets*/} -Sometimes you need to add UI widgets that aren't written to React. For example, let's say you're adding a map component to your page. It has a `setZoomLevel()` method, and you'd like to keep the zoom level in sync with a `zoomLevel` state variable in your React code. Your Effect would look similar to this: +Sometimes you need to add UI widgets that aren't written in React. For example, let's say you're adding a map component to your page. It has a `setZoomLevel()` method, and you'd like to keep the zoom level in sync with a `zoomLevel` state variable in your React code. Your Effect would look similar to this: ```js useEffect(() => { @@ -1600,7 +1600,7 @@ Each render's Effect has its own `ignore` variable. Initially, the `ignore` vari - Fetching `'Bob'` completes - The Effect from the `'Bob'` render **does not do anything because its `ignore` flag was set to `true`** -In addition to ignoring the result of an outdated API call, you can also use [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to cancel the requests that are no longer needed. However, by itself this is not enough to protect against race conditions. More asynchronous steps could be chained after the fetch, so using an explicit flag like `ignore` is the most reliable way to fix this type of problems. +In addition to ignoring the result of an outdated API call, you can also use [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to cancel the requests that are no longer needed. However, by itself this is not enough to protect against race conditions. More asynchronous steps could be chained after the fetch, so using an explicit flag like `ignore` is the most reliable way to fix this type of problem. diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md index 0f05a0569..822891e60 100644 --- a/src/content/learn/thinking-in-react.md +++ b/src/content/learn/thinking-in-react.md @@ -268,8 +268,8 @@ Now let's run through our strategy for them: 1. **Identify components that use state:** * `ProductTable` needs to filter the product list based on that state (search text and checkbox value). * `SearchBar` needs to display that state (search text and checkbox value). -1. **Find their common parent:** The first parent component both components share is `FilterableProductTable`. -2. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`. +2. **Find their common parent:** The first parent component both components share is `FilterableProductTable`. +3. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`. So the state values will live in `FilterableProductTable`. diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md index f18ec4939..c80c7f5fe 100644 --- a/src/content/learn/tutorial-tic-tac-toe.md +++ b/src/content/learn/tutorial-tic-tac-toe.md @@ -295,7 +295,7 @@ export default function Square() { } ``` -The _browser_ section should be displaying a square with a X in it like this: +The _browser_ section should be displaying a square with an X in it like this: ![x-filled square](../images/tutorial/x-filled-square.png) @@ -1133,7 +1133,7 @@ Calling the `setSquares` function lets React know the state of the component has -JavaScript supports [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) which means an inner function (e.g. `handleClick`) has access to variables and functions defined in a outer function (e.g. `Board`). The `handleClick` function can read the `squares` state and call the `setSquares` method because they are both defined inside of the `Board` function. +JavaScript supports [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) which means an inner function (e.g. `handleClick`) has access to variables and functions defined in an outer function (e.g. `Board`). The `handleClick` function can read the `squares` state and call the `setSquares` method because they are both defined inside of the `Board` function. @@ -1325,7 +1325,7 @@ Let's recap what happens when a user clicks the top left square on your board to 1. `handleClick` uses the argument (`0`) to update the first element of the `squares` array from `null` to `X`. 1. The `squares` state of the `Board` component was updated, so the `Board` and all of its children re-render. This causes the `value` prop of the `Square` component with index `0` to change from `null` to `X`. -In the end the user sees that the upper left square has changed from empty to having a `X` after clicking it. +In the end the user sees that the upper left square has changed from empty to having an `X` after clicking it. @@ -1406,7 +1406,7 @@ But wait, there's a problem. Try clicking on the same square multiple times: The `X` is overwritten by an `O`! While this would add a very interesting twist to the game, we're going to stick to the original rules for now. -When you mark a square with a `X` or an `O` you aren't first checking to see if the square already has a `X` or `O` value. You can fix this by *returning early*. You'll check to see if the square already has a `X` or an `O`. If the square is already filled, you will `return` in the `handleClick` function early--before it tries to update the board state. +When you mark a square with an `X` or an `O` you aren't first checking to see if the square already has an `X` or `O` value. You can fix this by *returning early*. You'll check to see if the square already has an `X` or an `O`. If the square is already filled, you will `return` in the `handleClick` function early--before it tries to update the board state. ```js {2,3,4} function handleClick(i) { @@ -1556,7 +1556,7 @@ It does not matter whether you define `calculateWinner` before or after the `Boa -You will call `calculateWinner(squares)` in the `Board` component's `handleClick` function to check if a player has won. You can perform this check at the same time you check if a user has clicked a square that already has a `X` or and `O`. We'd like to return early in both cases: +You will call `calculateWinner(squares)` in the `Board` component's `handleClick` function to check if a player has won. You can perform this check at the same time you check if a user has clicked a square that already has an `X` or an `O`. We'd like to return early in both cases: ```js {2} function handleClick(i) { @@ -2247,7 +2247,7 @@ body { -As you iterate through `history` array inside the function you passed to `map`, the `squares` argument goes through each element of `history`, and the `move` argument goes through each array index: `0`, `1`, `2`, …. (In most cases, you'd need the actual array elements, but to render a list of moves you will only need indexes.) +As you iterate through the `history` array inside the function you passed to `map`, the `squares` argument goes through each element of `history`, and the `move` argument goes through each array index: `0`, `1`, `2`, …. (In most cases, you'd need the actual array elements, but to render a list of moves you will only need indexes.) For each move in the tic-tac-toe game's history, you create a list item `
      • ` which contains a button ` -

        This error is not dismissible.

        -
      • - -
        - - -``` - -```css src/styles.css active -label, button { display: block; margin-bottom: 20px; } -html, body { min-height: 300px; } - -#error-dialog { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background-color: white; - padding: 15px; - opacity: 0.9; - text-wrap: wrap; - overflow: scroll; -} - -.text-red { - color: red; -} - -.-mb-20 { - margin-bottom: -20px; -} - -.mb-0 { - margin-bottom: 0; -} - -.mb-10 { - margin-bottom: 10px; -} - -pre { - text-wrap: wrap; -} - -pre.nowrap { - text-wrap: nowrap; -} +### Error logging in production {/*error-logging-in-production*/} -.hidden { - display: none; -} -``` +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 src/reportError.js hidden -function reportError({ title, error, componentStack, dismissable }) { - const errorDialog = document.getElementById("error-dialog"); - const errorTitle = document.getElementById("error-title"); - const errorMessage = document.getElementById("error-message"); - const errorBody = document.getElementById("error-body"); - const errorComponentStack = document.getElementById("error-component-stack"); - const errorStack = document.getElementById("error-stack"); - const errorClose = document.getElementById("error-close"); - const errorCause = document.getElementById("error-cause"); - const errorCauseMessage = document.getElementById("error-cause-message"); - const errorCauseStack = document.getElementById("error-cause-stack"); - const errorNotDismissible = document.getElementById("error-not-dismissible"); - - // Set the title - errorTitle.innerText = title; - - // Display error message and body - const [heading, body] = error.message.split(/\n(.*)/s); - errorMessage.innerText = heading; - if (body) { - errorBody.innerText = body; - } else { - errorBody.innerText = ''; - } - - // Display component stack - errorComponentStack.innerText = componentStack; - - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. - errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - - // Display the cause, if available - if (error.cause) { - errorCauseMessage.innerText = error.cause.message; - errorCauseStack.innerText = error.cause.stack; - errorCause.classList.remove('hidden'); - } else { - errorCause.classList.add('hidden'); - } - // Display the close button, if dismissible - if (dismissable) { - errorNotDismissible.classList.add('hidden'); - errorClose.classList.remove("hidden"); - } else { - errorNotDismissible.classList.remove('hidden'); - errorClose.classList.add("hidden"); - } - - // Show the dialog - errorDialog.classList.remove("hidden"); -} - -export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); -} - -export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); -} - -export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); -} -``` - -```js src/index.js active +```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]] import { createRoot } from "react-dom/client"; -import App from "./App.js"; -import {reportUncaughtError} from "./reportError"; -import "./styles.css"; +import { reportCaughtError } from "./reportError"; const container = document.getElementById("root"); const root = createRoot(container, { - onUncaughtError: (error, errorInfo) => { - if (error.message !== 'Known error') { - reportUncaughtError({ + onCaughtError: (error, errorInfo) => { + if (error.message !== "Known error") { + reportCaughtError({ error, - componentStack: errorInfo.componentStack + componentStack: errorInfo.componentStack, }); } - } -}); -root.render(); -``` - -```js src/App.js -import { useState } from 'react'; - -export default function App() { - const [throwError, setThrowError] = useState(false); - - if (throwError) { - foo.bar = 'baz'; - } - - return ( -
        - This error shows the error dialog: - -
        - ); -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0" }, - "main": "/index.js" -} -``` - - - - -### Displaying Error Boundary errors {/*displaying-error-boundary-errors*/} - - - -`onCaughtError` is only available in the latest React Canary release. - - - -By default, React will log all errors caught by an Error Boundary to `console.error`. To override this behavior, you can provide the optional `onCaughtError` root option to handle errors caught by an [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary): - -```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack"]] -import { createRoot } from 'react-dom/client'; - -const root = createRoot( - document.getElementById('root'), - { - onCaughtError: (error, errorInfo) => { - console.error( - 'Caught error', - error, - errorInfo.componentStack - ); - } - } -); -root.render(); +}); ``` The onCaughtError option is a function called with two arguments: -1. The error that was caught by the boundary. +1. The error that was thrown. 2. An errorInfo object that contains the componentStack of the error. -You can use the `onCaughtError` root option to display error dialogs or filter known errors from logging: +Together with `onUncaughtError` and `onRecoverableError`, you can can implement your own error reporting system: -```html index.html hidden - - - - My app - - - - - -
        - - -``` - -```css src/styles.css active -label, button { display: block; margin-bottom: 20px; } -html, body { min-height: 300px; } - -#error-dialog { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background-color: white; - padding: 15px; - opacity: 0.9; - text-wrap: wrap; - overflow: scroll; -} - -.text-red { - color: red; -} - -.-mb-20 { - margin-bottom: -20px; -} - -.mb-0 { - margin-bottom: 0; -} - -.mb-10 { - margin-bottom: 10px; -} - -pre { - text-wrap: wrap; -} - -pre.nowrap { - text-wrap: nowrap; -} - -.hidden { - display: none; +```js src/reportError.js +function reportError({ type, error, errorInfo }) { + // The specific implementation is up to you. + // `console.error()` is only used for demonstration purposes. + console.error(type, error, "Component Stack: "); + console.error("Component Stack: ", errorInfo.componentStack); } -``` - -```js src/reportError.js hidden -function reportError({ title, error, componentStack, dismissable }) { - const errorDialog = document.getElementById("error-dialog"); - const errorTitle = document.getElementById("error-title"); - const errorMessage = document.getElementById("error-message"); - const errorBody = document.getElementById("error-body"); - const errorComponentStack = document.getElementById("error-component-stack"); - const errorStack = document.getElementById("error-stack"); - const errorClose = document.getElementById("error-close"); - const errorCause = document.getElementById("error-cause"); - const errorCauseMessage = document.getElementById("error-cause-message"); - const errorCauseStack = document.getElementById("error-cause-stack"); - const errorNotDismissible = document.getElementById("error-not-dismissible"); - - // Set the title - errorTitle.innerText = title; - - // Display error message and body - const [heading, body] = error.message.split(/\n(.*)/s); - errorMessage.innerText = heading; - if (body) { - errorBody.innerText = body; - } else { - errorBody.innerText = ''; - } - // Display component stack - errorComponentStack.innerText = componentStack; - - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. - errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - - // Display the cause, if available - if (error.cause) { - errorCauseMessage.innerText = error.cause.message; - errorCauseStack.innerText = error.cause.stack; - errorCause.classList.remove('hidden'); - } else { - errorCause.classList.add('hidden'); +export function onCaughtErrorProd(error, errorInfo) { + if (error.message !== "Known error") { + reportError({ type: "Caught", error, errorInfo }); } - // Display the close button, if dismissible - if (dismissable) { - errorNotDismissible.classList.add('hidden'); - errorClose.classList.remove("hidden"); - } else { - errorNotDismissible.classList.remove('hidden'); - errorClose.classList.add("hidden"); - } - - // Show the dialog - errorDialog.classList.remove("hidden"); } -export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); +export function onUncaughtErrorProd(error, errorInfo) { + reportError({ type: "Uncaught", error, errorInfo }); } -export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); -} - -export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); +export function onRecoverableErrorProd(error, errorInfo) { + reportError({ type: "Recoverable", error, errorInfo }); } ``` ```js src/index.js active import { createRoot } from "react-dom/client"; import App from "./App.js"; -import {reportCaughtError} from "./reportError"; -import "./styles.css"; +import { + onCaughtErrorProd, + onRecoverableErrorProd, + onUncaughtErrorProd, +} from "./reportError"; const container = document.getElementById("root"); const root = createRoot(container, { - onCaughtError: (error, errorInfo) => { - if (error.message !== 'Known error') { - reportCaughtError({ - error, - componentStack: errorInfo.componentStack, - }); - } - } + // Keep in mind to remove these options in development to leverage + // React's default handlers or implement your own overlay for development. + // The handlers are only specfied unconditionally here for demonstration purposes. + onCaughtError: onCaughtErrorProd, + onRecoverableError: onRecoverableErrorProd, + onUncaughtError: onUncaughtErrorProd, }); root.render(); ``` ```js src/App.js -import { useState } from 'react'; -import { ErrorBoundary } from "react-error-boundary"; +import { Component, useState } from "react"; -export default function App() { - const [error, setError] = useState(null); - - function handleUnknown() { - setError("unknown"); - } - - function handleKnown() { - setError("known"); - } - - return ( - <> - { - setError(null); - }} - > - {error != null && } - This error will not show the error dialog: - - This error will show the error dialog: - - - - - ); +function Boom() { + foo.bar = "baz"; } -function fallbackRender({ resetErrorBoundary }) { - return ( -
        -

        Error Boundary

        -

        Something went wrong.

        - -
        - ); -} +class ErrorBoundary extends Component { + state = { hasError: false }; -function Throw({error}) { - if (error === "known") { - throw new Error('Known error') - } else { - foo.bar = 'baz'; + static getDerivedStateFromError(error) { + return { hasError: true }; } -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0", - "react-error-boundary": "4.0.3" - }, - "main": "/index.js" -} -``` - -
        - -### Displaying a dialog for recoverable errors {/*displaying-a-dialog-for-recoverable-errors*/} -React may automatically render a component a second time to attempt to recover from an error thrown in render. If successful, React will log a recoverable error to the console to notify the developer. To override this behavior, you can provide the optional `onRecoverableError` root option: - -```js [[1, 6, "onRecoverableError"], [2, 6, "error", 1], [3, 10, "error.cause"], [4, 6, "errorInfo"], [5, 11, "componentStack"]] -import { createRoot } from 'react-dom/client'; - -const root = createRoot( - document.getElementById('root'), - { - onRecoverableError: (error, errorInfo) => { - console.error( - 'Recoverable error', - error, - error.cause, - errorInfo.componentStack, - ); + render() { + if (this.state.hasError) { + return

        Something went wrong.

        ; } + return this.props.children; } -); -root.render(); -``` - -The onRecoverableError option is a function called with two arguments: - -1. The error that React throws. Some errors may include the original cause as error.cause. -2. An errorInfo object that contains the componentStack of the error. - -You can use the `onRecoverableError` root option to display error dialogs: - - - -```html index.html hidden - - - - My app - - - - - -
        - - -``` - -```css src/styles.css active -label, button { display: block; margin-bottom: 20px; } -html, body { min-height: 300px; } - -#error-dialog { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background-color: white; - padding: 15px; - opacity: 0.9; - text-wrap: wrap; - overflow: scroll; -} - -.text-red { - color: red; -} - -.-mb-20 { - margin-bottom: -20px; -} - -.mb-0 { - margin-bottom: 0; -} - -.mb-10 { - margin-bottom: 10px; -} - -pre { - text-wrap: wrap; -} - -pre.nowrap { - text-wrap: nowrap; -} - -.hidden { - display: none; } -``` -```js src/reportError.js hidden -function reportError({ title, error, componentStack, dismissable }) { - const errorDialog = document.getElementById("error-dialog"); - const errorTitle = document.getElementById("error-title"); - const errorMessage = document.getElementById("error-message"); - const errorBody = document.getElementById("error-body"); - const errorComponentStack = document.getElementById("error-component-stack"); - const errorStack = document.getElementById("error-stack"); - const errorClose = document.getElementById("error-close"); - const errorCause = document.getElementById("error-cause"); - const errorCauseMessage = document.getElementById("error-cause-message"); - const errorCauseStack = document.getElementById("error-cause-stack"); - const errorNotDismissible = document.getElementById("error-not-dismissible"); - - // Set the title - errorTitle.innerText = title; - - // Display error message and body - const [heading, body] = error.message.split(/\n(.*)/s); - errorMessage.innerText = heading; - if (body) { - errorBody.innerText = body; - } else { - errorBody.innerText = ''; - } - - // Display component stack - errorComponentStack.innerText = componentStack; - - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. - errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - - // Display the cause, if available - if (error.cause) { - errorCauseMessage.innerText = error.cause.message; - errorCauseStack.innerText = error.cause.stack; - errorCause.classList.remove('hidden'); - } else { - errorCause.classList.add('hidden'); - } - // Display the close button, if dismissible - if (dismissable) { - errorNotDismissible.classList.add('hidden'); - errorClose.classList.remove("hidden"); - } else { - errorNotDismissible.classList.remove('hidden'); - errorClose.classList.add("hidden"); - } - - // Show the dialog - errorDialog.classList.remove("hidden"); -} - -export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); -} - -export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); -} - -export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); -} -``` - -```js src/index.js active -import { createRoot } from "react-dom/client"; -import App from "./App.js"; -import {reportRecoverableError} from "./reportError"; -import "./styles.css"; - -const container = document.getElementById("root"); -const root = createRoot(container, { - onRecoverableError: (error, errorInfo) => { - reportRecoverableError({ - error, - cause: error.cause, - componentStack: errorInfo.componentStack, - }); - } -}); -root.render(); -``` - -```js src/App.js -import { useState } from 'react'; -import { ErrorBoundary } from "react-error-boundary"; - -// 🚩 Bug: Never do this. This will force an error. -let errorThrown = false; export default function App() { + const [triggerUncaughtError, settriggerUncaughtError] = useState(false); + const [triggerCaughtError, setTriggerCaughtError] = useState(false); + return ( <> - - {!errorThrown && } -

        This component threw an error, but recovered during a second render.

        -

        Since it recovered, no Error Boundary was shown, but onRecoverableError was used to show an error dialog.

        -
        - + + {triggerUncaughtError && } + + {triggerCaughtError && ( + + + + )} ); } - -function fallbackRender() { - return ( -
        -

        Error Boundary

        -

        Something went wrong.

        -
        - ); -} - -function Throw({error}) { - // Simulate an external value changing during concurrent render. - errorThrown = true; - foo.bar = 'baz'; -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0", - "react-error-boundary": "4.0.3" - }, - "main": "/index.js" -} ```
        - ---- ## Troubleshooting {/*troubleshooting*/} ### I've created a root, but nothing is displayed {/*ive-created-a-root-but-nothing-is-displayed*/} diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md index cc30ce22c..b74e2c38e 100644 --- a/src/content/reference/react-dom/client/hydrateRoot.md +++ b/src/content/reference/react-dom/client/hydrateRoot.md @@ -41,8 +41,8 @@ React will attach to the HTML that exists inside the `domNode`, and take over ma * **optional** `options`: An object with options for this React root. - * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`. - * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`. + * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`. + * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`. * **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with the `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`. * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server. @@ -99,7 +99,7 @@ An app fully built with React will usually not have any calls to `root.unmount`. This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. You need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't clean up and free up resources like subscriptions. -Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. +Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. #### Parameters {/*root-unmount-parameters*/} @@ -270,7 +270,7 @@ export default function App() { -This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates. +This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. React will **not** attempt to patch mismatched text content. --- @@ -374,578 +374,126 @@ export default function App({counter}) { It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/reference/react/useState) inside one of the components instead. -### Show a dialog for uncaught errors {/*show-a-dialog-for-uncaught-errors*/} +### Error logging in production {/*error-logging-in-production*/} - +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`: -`onUncaughtError` is only available in the latest React Canary release. - - - -By default, React will log all uncaught errors to the console. To implement your own error reporting, you can provide the optional `onUncaughtError` root option: - -```js [[1, 7, "onUncaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack"]] -import { hydrateRoot } from 'react-dom/client'; +```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 root = hydrateRoot( - document.getElementById('root'), - , - { - onUncaughtError: (error, errorInfo) => { - console.error( - 'Uncaught error', +const container = document.getElementById("root"); +const root = hydrateRoot(container, , { + onCaughtError: (error, errorInfo) => { + if (error.message !== "Known error") { + reportCaughtError({ error, - errorInfo.componentStack - ); + componentStack: errorInfo.componentStack, + }); } - } -); -root.render(); + }, +}); ``` -The onUncaughtError option is a function called with two arguments: +The onCaughtError option is a function called with two arguments: 1. The error that was thrown. 2. An errorInfo object that contains the componentStack of the error. -You can use the `onUncaughtError` root option to display error dialogs: +Together with `onUncaughtError` and `onRecoverableError`, you can implement your own error reporting system: -```html index.html hidden - - - - My app - - - - - -
        This error shows the error dialog:
        - - -``` - -```css src/styles.css active -label, button { display: block; margin-bottom: 20px; } -html, body { min-height: 300px; } - -#error-dialog { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background-color: white; - padding: 15px; - opacity: 0.9; - text-wrap: wrap; - overflow: scroll; -} - -.text-red { - color: red; -} - -.-mb-20 { - margin-bottom: -20px; -} - -.mb-0 { - margin-bottom: 0; -} - -.mb-10 { - margin-bottom: 10px; -} - -pre { - text-wrap: wrap; -} - -pre.nowrap { - text-wrap: nowrap; -} - -.hidden { - display: none; +```js src/reportError.js +function reportError({ type, error, errorInfo }) { + // The specific implementation is up to you. + // `console.error()` is only used for demonstration purposes. + console.error(type, error, "Component Stack: "); + console.error("Component Stack: ", errorInfo.componentStack); } -``` - -```js src/reportError.js hidden -function reportError({ title, error, componentStack, dismissable }) { - const errorDialog = document.getElementById("error-dialog"); - const errorTitle = document.getElementById("error-title"); - const errorMessage = document.getElementById("error-message"); - const errorBody = document.getElementById("error-body"); - const errorComponentStack = document.getElementById("error-component-stack"); - const errorStack = document.getElementById("error-stack"); - const errorClose = document.getElementById("error-close"); - const errorCause = document.getElementById("error-cause"); - const errorCauseMessage = document.getElementById("error-cause-message"); - const errorCauseStack = document.getElementById("error-cause-stack"); - const errorNotDismissible = document.getElementById("error-not-dismissible"); - - // Set the title - errorTitle.innerText = title; - - // Display error message and body - const [heading, body] = error.message.split(/\n(.*)/s); - errorMessage.innerText = heading; - if (body) { - errorBody.innerText = body; - } else { - errorBody.innerText = ''; - } - // Display component stack - errorComponentStack.innerText = componentStack; - - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. - errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - - // Display the cause, if available - if (error.cause) { - errorCauseMessage.innerText = error.cause.message; - errorCauseStack.innerText = error.cause.stack; - errorCause.classList.remove('hidden'); - } else { - errorCause.classList.add('hidden'); - } - // Display the close button, if dismissible - if (dismissable) { - errorNotDismissible.classList.add('hidden'); - errorClose.classList.remove("hidden"); - } else { - errorNotDismissible.classList.remove('hidden'); - errorClose.classList.add("hidden"); +export function onCaughtErrorProd(error, errorInfo) { + if (error.message !== "Known error") { + reportError({ type: "Caught", error, errorInfo }); } - - // Show the dialog - errorDialog.classList.remove("hidden"); } -export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); +export function onUncaughtErrorProd(error, errorInfo) { + reportError({ type: "Uncaught", error, errorInfo }); } -export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); -} - -export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); +export function onRecoverableErrorProd(error, errorInfo) { + reportError({ type: "Recoverable", error, errorInfo }); } ``` ```js src/index.js active import { hydrateRoot } from "react-dom/client"; import App from "./App.js"; -import {reportUncaughtError} from "./reportError"; -import "./styles.css"; -import {renderToString} from 'react-dom/server'; +import { + onCaughtErrorProd, + onRecoverableErrorProd, + onUncaughtErrorProd, +} from "./reportError"; const container = document.getElementById("root"); -const root = hydrateRoot(container, , { - onUncaughtError: (error, errorInfo) => { - if (error.message !== 'Known error') { - reportUncaughtError({ - error, - componentStack: errorInfo.componentStack - }); - } - } +hydrateRoot(container, , { + // Keep in mind to remove these options in development to leverage + // React's default handlers or implement your own overlay for development. + // The handlers are only specfied unconditionally here for demonstration purposes. + onCaughtError: onCaughtErrorProd, + onRecoverableError: onRecoverableErrorProd, + onUncaughtError: onUncaughtErrorProd, }); ``` ```js src/App.js -import { useState } from 'react'; - -export default function App() { - const [throwError, setThrowError] = useState(false); - - if (throwError) { - foo.bar = 'baz'; - } - - return ( -
        - This error shows the error dialog: - -
        - ); -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0" - }, - "main": "/index.js" -} -``` - -
        - - -### Displaying Error Boundary errors {/*displaying-error-boundary-errors*/} - - - -`onCaughtError` is only available in the latest React Canary release. - - - -By default, React will log all errors caught by an Error Boundary to `console.error`. To override this behavior, you can provide the optional `onCaughtError` root option for errors caught by an [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary): - -```js [[1, 7, "onCaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack"]] -import { hydrateRoot } from 'react-dom/client'; - -const root = hydrateRoot( - document.getElementById('root'), - , - { - onCaughtError: (error, errorInfo) => { - console.error( - 'Caught error', - error, - errorInfo.componentStack - ); - } - } -); -root.render(); -``` - -The onCaughtError option is a function called with two arguments: - -1. The error that was caught by the boundary. -2. An errorInfo object that contains the componentStack of the error. - -You can use the `onCaughtError` root option to display error dialogs or filter known errors from logging: - - - -```html index.html hidden - - - - My app - - - - - -
        This error will not show the error dialog:This error will show the error dialog:
        - - -``` - -```css src/styles.css active -label, button { display: block; margin-bottom: 20px; } -html, body { min-height: 300px; } - -#error-dialog { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background-color: white; - padding: 15px; - opacity: 0.9; - text-wrap: wrap; - overflow: scroll; -} - -.text-red { - color: red; -} - -.-mb-20 { - margin-bottom: -20px; -} - -.mb-0 { - margin-bottom: 0; -} - -.mb-10 { - margin-bottom: 10px; -} - -pre { - text-wrap: wrap; -} - -pre.nowrap { - text-wrap: nowrap; -} +import { Component, useState } from "react"; -.hidden { - display: none; +function Boom() { + foo.bar = "baz"; } -``` -```js src/reportError.js hidden -function reportError({ title, error, componentStack, dismissable }) { - const errorDialog = document.getElementById("error-dialog"); - const errorTitle = document.getElementById("error-title"); - const errorMessage = document.getElementById("error-message"); - const errorBody = document.getElementById("error-body"); - const errorComponentStack = document.getElementById("error-component-stack"); - const errorStack = document.getElementById("error-stack"); - const errorClose = document.getElementById("error-close"); - const errorCause = document.getElementById("error-cause"); - const errorCauseMessage = document.getElementById("error-cause-message"); - const errorCauseStack = document.getElementById("error-cause-stack"); - const errorNotDismissible = document.getElementById("error-not-dismissible"); - - // Set the title - errorTitle.innerText = title; - - // Display error message and body - const [heading, body] = error.message.split(/\n(.*)/s); - errorMessage.innerText = heading; - if (body) { - errorBody.innerText = body; - } else { - errorBody.innerText = ''; - } +class ErrorBoundary extends Component { + state = { hasError: false }; - // Display component stack - errorComponentStack.innerText = componentStack; - - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. - errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - - // Display the cause, if available - if (error.cause) { - errorCauseMessage.innerText = error.cause.message; - errorCauseStack.innerText = error.cause.stack; - errorCause.classList.remove('hidden'); - } else { - errorCause.classList.add('hidden'); - } - // Display the close button, if dismissible - if (dismissable) { - errorNotDismissible.classList.add('hidden'); - errorClose.classList.remove("hidden"); - } else { - errorNotDismissible.classList.remove('hidden'); - errorClose.classList.add("hidden"); + static getDerivedStateFromError(error) { + return { hasError: true }; } - - // Show the dialog - errorDialog.classList.remove("hidden"); -} -export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); -} - -export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); -} - -export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); -} -``` - -```js src/index.js active -import { hydrateRoot } from "react-dom/client"; -import App from "./App.js"; -import {reportCaughtError} from "./reportError"; -import "./styles.css"; - -const container = document.getElementById("root"); -const root = hydrateRoot(container, , { - onCaughtError: (error, errorInfo) => { - if (error.message !== 'Known error') { - reportCaughtError({ - error, - componentStack: errorInfo.componentStack - }); + render() { + if (this.state.hasError) { + return

        Something went wrong.

        ; } + return this.props.children; } -}); -``` - -```js src/App.js -import { useState } from 'react'; -import { ErrorBoundary } from "react-error-boundary"; +} export default function App() { - const [error, setError] = useState(null); - - function handleUnknown() { - setError("unknown"); - } + const [triggerUncaughtError, settriggerUncaughtError] = useState(false); + const [triggerCaughtError, setTriggerCaughtError] = useState(false); - function handleKnown() { - setError("known"); - } - return ( <> - { - setError(null); - }} - > - {error != null && } - This error will not show the error dialog: - - This error will show the error dialog: - - - + + {triggerUncaughtError && } + + {triggerCaughtError && ( + + + + )} ); } - -function fallbackRender({ resetErrorBoundary }) { - return ( -
        -

        Error Boundary

        -

        Something went wrong.

        - -
        - ); -} - -function Throw({error}) { - if (error === "known") { - throw new Error('Known error') - } else { - foo.bar = 'baz'; - } -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0", - "react-error-boundary": "4.0.3" - }, - "main": "/index.js" -} -``` - -
        - -### Show a dialog for recoverable hydration mismatch errors {/*show-a-dialog-for-recoverable-hydration-mismatch-errors*/} - -When React encounters a hydration mismatch, it will automatically attempt to recover by rendering on the client. By default, React will log hydration mismatch errors to `console.error`. To override this behavior, you can provide the optional `onRecoverableError` root option: - -```js [[1, 7, "onRecoverableError"], [2, 7, "error", 1], [3, 11, "error.cause", 1], [4, 7, "errorInfo"], [5, 12, "componentStack"]] -import { hydrateRoot } from 'react-dom/client'; - -const root = hydrateRoot( - document.getElementById('root'), - , - { - onRecoverableError: (error, errorInfo) => { - console.error( - 'Caught error', - error, - error.cause, - errorInfo.componentStack - ); - } - } -); ``` -The onRecoverableError option is a function called with two arguments: - -1. The error React throws. Some errors may include the original cause as error.cause. -2. An errorInfo object that contains the componentStack of the error. - -You can use the `onRecoverableError` root option to display error dialogs for hydration mismatches: - - - -```html index.html hidden +```html public/index.html hidden @@ -953,226 +501,12 @@ You can use the `onRecoverableError` root option to display error dialogs for hy - - -
        Server
        +
        Server content before hydration.
        ``` - -```css src/styles.css active -label, button { display: block; margin-bottom: 20px; } -html, body { min-height: 300px; } - -#error-dialog { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background-color: white; - padding: 15px; - opacity: 0.9; - text-wrap: wrap; - overflow: scroll; -} - -.text-red { - color: red; -} - -.-mb-20 { - margin-bottom: -20px; -} - -.mb-0 { - margin-bottom: 0; -} - -.mb-10 { - margin-bottom: 10px; -} - -pre { - text-wrap: wrap; -} - -pre.nowrap { - text-wrap: nowrap; -} - -.hidden { - display: none; -} -``` - -```js src/reportError.js hidden -function reportError({ title, error, componentStack, dismissable }) { - const errorDialog = document.getElementById("error-dialog"); - const errorTitle = document.getElementById("error-title"); - const errorMessage = document.getElementById("error-message"); - const errorBody = document.getElementById("error-body"); - const errorComponentStack = document.getElementById("error-component-stack"); - const errorStack = document.getElementById("error-stack"); - const errorClose = document.getElementById("error-close"); - const errorCause = document.getElementById("error-cause"); - const errorCauseMessage = document.getElementById("error-cause-message"); - const errorCauseStack = document.getElementById("error-cause-stack"); - const errorNotDismissible = document.getElementById("error-not-dismissible"); - - // Set the title - errorTitle.innerText = title; - - // Display error message and body - const [heading, body] = error.message.split(/\n(.*)/s); - errorMessage.innerText = heading; - if (body) { - errorBody.innerText = body; - } else { - errorBody.innerText = ''; - } - - // Display component stack - errorComponentStack.innerText = componentStack; - - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. - errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - - // Display the cause, if available - if (error.cause) { - errorCauseMessage.innerText = error.cause.message; - errorCauseStack.innerText = error.cause.stack; - errorCause.classList.remove('hidden'); - } else { - errorCause.classList.add('hidden'); - } - // Display the close button, if dismissible - if (dismissable) { - errorNotDismissible.classList.add('hidden'); - errorClose.classList.remove("hidden"); - } else { - errorNotDismissible.classList.remove('hidden'); - errorClose.classList.add("hidden"); - } - - // Show the dialog - errorDialog.classList.remove("hidden"); -} - -export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); -} - -export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); -} - -export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); -} -``` - -```js src/index.js active -import { hydrateRoot } from "react-dom/client"; -import App from "./App.js"; -import {reportRecoverableError} from "./reportError"; -import "./styles.css"; - -const container = document.getElementById("root"); -const root = hydrateRoot(container, , { - onRecoverableError: (error, errorInfo) => { - reportRecoverableError({ - error, - cause: error.cause, - componentStack: errorInfo.componentStack - }); - } -}); -``` - -```js src/App.js -import { useState } from 'react'; -import { ErrorBoundary } from "react-error-boundary"; - -export default function App() { - const [error, setError] = useState(null); - - function handleUnknown() { - setError("unknown"); - } - - function handleKnown() { - setError("known"); - } - - return ( - {typeof window !== 'undefined' ? 'Client' : 'Server'} - ); -} - -function fallbackRender({ resetErrorBoundary }) { - return ( -
        -

        Error Boundary

        -

        Something went wrong.

        - -
        - ); -} - -function Throw({error}) { - if (error === "known") { - throw new Error('Known error') - } else { - foo.bar = 'baz'; - } -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0", - "react-error-boundary": "4.0.3" - }, - "main": "/index.js" -} -``` -
        ## Troubleshooting {/*troubleshooting*/} diff --git a/src/content/reference/react-dom/components/common.md b/src/content/reference/react-dom/components/common.md index 62ee08139..9d1533213 100644 --- a/src/content/reference/react-dom/components/common.md +++ b/src/content/reference/react-dom/components/common.md @@ -246,43 +246,41 @@ These events fire for resources like [`