diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml
index b1ef428d0..83e7f2e8a 100644
--- a/.github/workflows/analyze.yml
+++ b/.github/workflows/analyze.yml
@@ -7,6 +7,8 @@ on:
- main # change this if your default branch is named differently
workflow_dispatch:
+permissions: {}
+
jobs:
analyze:
runs-on: ubuntu-latest
@@ -23,7 +25,7 @@ jobs:
- name: Restore cached node_modules
uses: actions/cache@v4
with:
- path: "**/node_modules"
+ path: '**/node_modules'
key: node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
- name: Install deps
@@ -55,7 +57,7 @@ jobs:
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
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
index 9d83081cc..a553b23a0 100644
--- a/.github/workflows/discord_notify.yml
+++ b/.github/workflows/discord_notify.yml
@@ -1,12 +1,17 @@
name: Discord Notify
on:
- pull_request_target:
- types: [labeled]
+ pull_request:
+ 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 }}
is_remote: true
diff --git a/.github/workflows/label_core_team_prs.yml b/.github/workflows/label_core_team_prs.yml
index 3d9fa2be1..6099b8fcb 100644
--- a/.github/workflows/label_core_team_prs.yml
+++ b/.github/workflows/label_core_team_prs.yml
@@ -1,7 +1,9 @@
name: Label Core Team PRs
on:
- pull_request_target:
+ pull_request:
+
+permissions: {}
env:
TZ: /usr/share/zoneinfo/America/Los_Angeles
@@ -11,6 +13,9 @@ env:
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 }}
is_remote: true
@@ -19,6 +24,11 @@ jobs:
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
diff --git a/.github/workflows/site_lint.yml b/.github/workflows/site_lint.yml
index 36f7642c9..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
@@ -25,7 +27,7 @@ jobs:
- name: Restore cached node_modules
uses: actions/cache@v4
with:
- path: "**/node_modules"
+ path: '**/node_modules'
key: node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
- name: Install deps
diff --git a/next-env.d.ts b/next-env.d.ts
index 52e831b43..3cd7048ed 100644
--- a/next-env.d.ts
+++ b/next-env.d.ts
@@ -1,5 +1,6 @@
///
///
+///
// NOTE: This file should not be edited
-// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
+// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/src/components/MDX/CodeBlock/CodeBlock.tsx b/src/components/MDX/CodeBlock/CodeBlock.tsx
index 1fd9a8a90..42165c57d 100644
--- a/src/components/MDX/CodeBlock/CodeBlock.tsx
+++ b/src/components/MDX/CodeBlock/CodeBlock.tsx
@@ -336,6 +336,7 @@ function getInlineDecorators(
line.step === 3,
'bg-green-40 border-green-40 text-green-60 dark:text-green-30':
line.step === 4,
+ // TODO: Some codeblocks use up to 6 steps.
}
),
})
diff --git a/src/content/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022.md b/src/content/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022.md
index 80fcb78e6..1aaa94ec1 100644
--- a/src/content/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022.md
+++ b/src/content/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022.md
@@ -27,7 +27,7 @@ We announced an [experimental demo of React Server Components](https://legacy.re
In particular, we’re abandoning the idea of having forked I/O libraries (eg react-fetch), and instead adopting an async/await model for better compatibility. This doesn’t technically block RSC’s release because you can also use routers for data fetching. Another change is that we’re also moving away from the file extension approach in favor of [annotating boundaries](https://github.com/reactjs/rfcs/pull/189#issuecomment-1116482278).
-We’re working together with Vercel and Shopify to unify bundler support for shared semantics in both Webpack and Vite. Before launch, we want to make sure that the semantics of RSCs are the same across the whole React ecosystem. This is the major blocker for reaching stable.
+We’re working together with Vercel and Shopify to unify bundler support for shared semantics in both webpack and Vite. Before launch, we want to make sure that the semantics of RSCs are the same across the whole React ecosystem. This is the major blocker for reaching stable.
## Asset Loading {/*asset-loading*/}
diff --git a/src/content/blog/2024/04/25/react-19-upgrade-guide.md b/src/content/blog/2024/04/25/react-19-upgrade-guide.md
index fbc4e378c..cb83a6176 100644
--- a/src/content/blog/2024/04/25/react-19-upgrade-guide.md
+++ b/src/content/blog/2024/04/25/react-19-upgrade-guide.md
@@ -24,7 +24,7 @@ To help make the upgrade to React 19 easier, we've published a `react@18.3` rele
We recommend upgrading to React 18.3 first to help identify any issues before upgrading to React 19.
-For a list of changes in 18.3 see the [Release Notes](https://github.com/facebook/react/blob/main/CHANGELOG.md).
+For a list of changes in 18.3 see the [Release Notes](https://github.com/facebook/react/blob/main/CHANGELOG.md#1830-april-25-2024).
@@ -113,7 +113,7 @@ This will run the following codemods from `react-codemod`:
- [`replace-string-ref`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-string-ref)
- [`replace-act-import`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-act-import)
- [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-use-form-state)
-- [`prop-types-typescript`](https://codemod.com/registry/react-prop-types-typescript)
+- [`prop-types-typescript`](https://github.com/reactjs/react-codemod#react-proptypes-to-prop-types)
This does not include the TypeScript changes. See [TypeScript changes](#typescript-changes) below.
diff --git a/src/content/blog/2025/02/14/sunsetting-create-react-app.md b/src/content/blog/2025/02/14/sunsetting-create-react-app.md
new file mode 100644
index 000000000..9ced6231c
--- /dev/null
+++ b/src/content/blog/2025/02/14/sunsetting-create-react-app.md
@@ -0,0 +1,320 @@
+---
+title: "Sunsetting Create React App"
+author: Matt Carroll and Ricky Hanlon
+date: 2025/02/14
+description: 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.
+---
+
+February 14, 2025 by [Matt Carroll](https://twitter.com/mattcarrollcode) and [Ricky Hanlon](https://bsky.app/profile/ricky.fm)
+
+---
+
+
+
+Today, we’re deprecating [Create React App](https://create-react-app.dev/) for new apps, and encouraging existing apps to migrate to a [framework](#how-to-migrate-to-a-framework), or to [migrate to a build tool](#how-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](/learn/build-a-react-app-from-scratch).
+
+
+
+-----
+
+When we released Create React App in 2016, there was no clear way to build a new React app.
+
+To create a React app, you had to install a bunch of tools and wire them up together yourself to support basic features like JSX, linting, and hot reloading. This was very tricky to do correctly, so the [community](https://github.com/react-boilerplate/react-boilerplate) [created](https://github.com/kriasoft/react-starter-kit) [boilerplates](https://github.com/petehunt/react-boilerplate) for [common](https://github.com/gaearon/react-hot-boilerplate) [setups](https://github.com/erikras/react-redux-universal-hot-example). However, boilerplates were difficult to update and fragmentation made it difficult for React to release new features.
+
+Create React App solved these problems by combining several tools into a single recommended configuration. This allowed apps a simple way to upgrade to new tooling features, and allowed the React team to deploy non-trivial tooling changes (Fast Refresh support, React Hooks lint rules) to the broadest possible audience.
+
+This model became so popular that there's an entire category of tools working this way today.
+
+## Deprecating Create React App {/*deprecating-create-react-app*/}
+
+Although Create React App makes it easy to get started, [there are several limitations](#limitations-of-build-tools) that make it difficult to build high performant production apps. In principle, we could solve these problems by essentially evolving it into a [framework](#why-we-recommend-frameworks).
+
+However, since Create React App currently has no active maintainers, and there are many existing frameworks that solve these problems already, we’ve decided to deprecate Create React App.
+
+Starting today, if you install a new app, you will see a deprecation warning:
+
+
+
+
+create-react-app is deprecated.
+{'\n\n'}
+You can find a list of up-to-date React frameworks on react.dev
+For more info see: react.dev/link/cra
+{'\n\n'}
+This error message will only be shown once per install.
+
+
+
+
+We've also added a deprecation notice to the Create React App [website](https://create-react-app.dev/) and GitHub [repo](https://github.com/facebook/create-react-app). Create React App will continue working in maintenance mode, and we've published a new version of Create React App to work with React 19.
+
+## How to Migrate to a Framework {/*how-to-migrate-to-a-framework*/}
+We recommend [creating new React apps](/learn/creating-a-react-app) with a framework. All the frameworks we recommend support client-side rendering ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)) and single-page apps ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), and can be deployed to a CDN or static hosting service without a server.
+
+For existing apps, these guides will help you migrate to a client-only SPA:
+
+* [Next.js’ Create React App migration guide](https://nextjs.org/docs/app/building-your-application/upgrading/from-create-react-app)
+* [React Router’s framework adoption guide](https://reactrouter.com/upgrading/component-routes).
+* [Expo webpack to Expo Router migration guide](https://docs.expo.dev/router/migrate/from-expo-webpack/)
+
+## How to Migrate to a Build Tool {/*how-to-migrate-to-a-build-tool*/}
+
+If your app has unusual constraints, or you prefer to solve these problems by building your own framework, or you just want to learn how react works from scratch, you can roll your own custom setup with React using Vite, Parcel or Rsbuild.
+
+For existing apps, these guides will help you migrate to a build tool:
+
+* [Vite Create React App migration guide](https://www.robinwieruch.de/vite-create-react-app/)
+* [Parcel Create React App migration guide](https://parceljs.org/migration/cra/)
+* [Rsbuild Create React App migration guide](https://rsbuild.dev/guide/migration/cra)
+
+To help get started with Vite, Parcel or Rsbuild, we've added new docs for [Building a React App from Scratch](/learn/build-a-react-app-from-scratch).
+
+
+
+#### Do I need a framework? {/*do-i-need-a-framework*/}
+
+Most apps would benefit from a framework, but there are valid cases to build a React app from scratch. A good rule of thumb is if your app needs routing, you would probably benefit from a framework.
+
+Just like Svelte has Sveltekit, Vue has Nuxt, and Solid has SolidStart, [React recommends using a framework](#why-we-recommend-frameworks) that fully integrates routing into features like data-fetching and code-splitting out of the box. This avoids the pain of needing to write your own complex configurations and essentially build a framework yourself.
+
+However, you can always [build a React app from scratch](/learn/build-a-react-app-from-scratch) using a build tool like Vite, Parcel, or Rsbuild.
+
+
+
+Continue reading to learn more about the [limitations of build tools](#limitations-of-build-tools) and [why we recommend frameworks](#why-we-recommend-frameworks).
+
+## Limitations of Build Tools {/*limitations-of-build-tools*/}
+
+Create React App and build tools like it make it easy to get started building a React app. After running `npx create-react-app my-app`, you get a fully configured React app with a development server, linting, and a production build.
+
+For example, if you're building an internal admin tool, you can start with a landing page:
+
+```js
+export default function App() {
+ return (
+
+
Welcome to the Admin Tool!
+
+ )
+}
+```
+
+This allows you to immediately start coding in React with features like JSX, default linting rules, and a bundler to run in both development and production. However, this setup is missing the tools you need to build a real production app.
+
+Most production apps need solutions to problems like routing, data fetching, and code splitting.
+
+### Routing {/*routing*/}
+
+Create React App does not include a specific routing solution. If you're just getting started, one option is to use `useState` to switch between routes. But doing this means that you can't share links to your app - every link would go to the same page - and structuring your app becomes difficult over time:
+
+```js
+import {useState} from 'react';
+
+import Home from './Home';
+import Dashboard from './Dashboard';
+
+export default function App() {
+ // ❌ Routing in state does not create URLs
+ const [route, setRoute] = useState('home');
+ return (
+
+ )
+}
+```
+
+This is why most apps that use Create React App solve add routing with a routing library like [React Router](https://reactrouter.com/) or [Tanstack Router](https://tanstack.com/router/latest). With a routing library, you can add additional routes to the app, which provides opinions on the structure of your app, and allows you to start sharing links to routes. For example, with React Router you can define routes:
+
+```js
+import {RouterProvider, createBrowserRouter} from 'react-router';
+
+import Home from './Home';
+import Dashboard from './Dashboard';
+
+// ✅ Each route has it's own URL
+const router = createBrowserRouter([
+ {path: '/', element: },
+ {path: '/dashboard', element: }
+]);
+
+export default function App() {
+ return (
+
+ )
+}
+```
+
+With this change, you can share a link to `/dashboard` and the app will navigate to the dashboard page . Once you have a routing library, you can add additional features like nested routes, route guards, and route transitions, which are difficult to implement without a routing library.
+
+There's a tradeoff being made here: the routing library adds complexity to the app, but it also adds features that are difficult to implement without it.
+
+### Data Fetching {/*data-fetching*/}
+
+Another common problem in Create React App is data fetching. Create React App does not include a specific data fetching solution. If you're just getting started, a common option is to use `fetch` in an effect to load data.
+
+But doing this means that the data is fetched after the component renders, which can cause network waterfalls. Network waterfalls are caused by fetching data when your app renders instead of in parallel while the code is downloading:
+
+```js
+export default function Dashboard() {
+ const [data, setData] = useState(null);
+
+ // ❌ Fetching data in a component causes network waterfalls
+ useEffect(() => {
+ fetch('/api/data')
+ .then(response => response.json())
+ .then(data => setData(data));
+ }, []);
+
+ return (
+
+ {data.map(item =>
{item.name}
)}
+
+ )
+}
+```
+
+Fetching in an effect means the user has to wait longer to see the content, even though the data could have been fetched earlier. To solve this, you can use a data fetching library like [React Query](https://react-query.tanstack.com/), [SWR](https://swr.vercel.app/), [Apollo](https://www.apollographql.com/docs/react), or [Relay](https://relay.dev/) which provide options to prefetch data so the request is started before the component renders.
+
+These libraries work best when integrated with your routing "loader" pattern to specify data dependencies at the route level, which allows the router to optimize your data fetches:
+
+```js
+export async function loader() {
+ const response = await fetch(`/api/data`);
+ const data = await response.json();
+ return data;
+}
+
+// ✅ Fetching data in parallel while the code is downloading
+export default function Dashboard({loaderData}) {
+ return (
+
+ {loaderData.map(item =>
{item.name}
)}
+
+ )
+}
+```
+
+On initial load, the router can fetch the data immediately before the route is rendered. As the user navigates around the app, the router is able to fetch both the data and the route at the same time, parallelizing the fetches. This reduces the time it takes to see the content on the screen, and can improve the user experience.
+
+However, this requires correctly configuring the loaders in your app and trades off complexity for performance.
+
+### Code Splitting {/*code-splitting*/}
+
+Another common problem in Create React App is [code splitting](https://www.patterns.dev/vanilla/bundle-splitting). Create React App does not include a specific code splitting solution. If you're just getting started, you might not consider code splitting at all.
+
+This means your app is shipped as a single bundle:
+
+```txt
+- bundle.js 75kb
+```
+
+But for ideal performance, you should "split" your code into separate bundles so the user only needs to download what they need. This decreases the time the user needs to wait to load your app, by only downloading the code they need to see the page they are on.
+
+```txt
+- core.js 25kb
+- home.js 25kb
+- dashboard.js 25kb
+```
+
+One way to do code-splitting is with `React.lazy`. However, this means that the code is not fetched until the component renders, which can cause network waterfalls. A more optimal solution is to use a router feature that fetches the code in parallel while the code is downloading. For example, React Router provides a `lazy` option to specify that a route should be code split and optimize when it is loaded:
+
+```js
+import Home from './Home';
+import Dashboard from './Dashboard';
+
+// ✅ Routes are downloaded before rendering
+const router = createBrowserRouter([
+ {path: '/', lazy: () => import('./Home')},
+ {path: '/dashboard', lazy: () => import('Dashboard')}
+]);
+```
+
+Optimized code-splitting is tricky to get right, and it's easy to make mistakes that can cause the user to download more code than they need. It works best when integrated with your router and data loading solutions to maximize caching, parallelize fetches, and support ["import on interaction"](https://www.patterns.dev/vanilla/import-on-interaction) patterns.
+
+### And more... {/*and-more*/}
+
+These are just a few examples of the limitations of Create React App.
+
+Once you've integrated routing, data-fetching, and code splitting, you now also need to consider pending states, navigation interruptions, error messages to the user, and revalidation of the data. There are entire categories of problems that users need to solve like:
+
+
+
+
Accessibility
+
Asset loading
+
Authentication
+
Caching
+
+
+
Error handling
+
Mutating data
+
Navigations
+
Optimistic updates
+
+
+
Progressive enhancement
+
Server-side rendering
+
Static site generation
+
Streaming
+
+
+
+All of these work together to create the most optimal [loading sequence](https://www.patterns.dev/vanilla/loading-sequence).
+
+Solving each of these problems individually in Create React App can be difficult as each problem is interconnected with the others and can require deep expertise in problem areas users may not be familiar with. In order to solve these problems, users end up building their own bespoke solutions on top of Create React App, which was the problem Create React App originally tried to solve.
+
+## Why we Recommend Frameworks {/*why-we-recommend-frameworks*/}
+
+Although you could solve all these pieces yourself in a build tool like Create React App, Vite, or Parcel, it is hard to do well. Just like when Create React App itself integrated several build tools together, you need a tool to integrate all of these features together to provide the best experience to users.
+
+This category of tools that integrates build tools, rendering, routing, data fetching, and code splitting are known as "frameworks" -- or if you prefer to call React itself a framework, you might call them "metaframeworks".
+
+Frameworks impose some opinions about structuring your app in order to provide a much better user experience, in the same way build tools impose some opinions to make tooling easier. This is why we started recommending frameworks like [Next.js](https://nextjs.org/), [React Router](https://reactrouter.com/), and [Expo](https://expo.dev/) for new projects.
+
+Frameworks provide the same getting started experience as Create React App, but also provide solutions to problems users need to solve anyway in real production apps.
+
+
+
+#### Server rendering is optional {/*server-rendering-is-optional*/}
+
+The frameworks we recommend all provide the option to create a [client-side rendered (CSR)](https://developer.mozilla.org/en-US/docs/Glossary/CSR) app.
+
+In some cases, CSR is the right choice for a page, but many times it's not. Even if most of your app is client-side, there are often individual pages that could benefit from server rendering features like [static-site generation (SSG)](https://developer.mozilla.org/en-US/docs/Glossary/SSG) or [server-side rendering (SSR)](https://developer.mozilla.org/en-US/docs/Glossary/SSR), for example a Terms of Service page, or documentation.
+
+Server rendering generally sends less JavaScript to the client, and a full HTML document which produces a faster [First Contentful Paint (FCP)](https://web.dev/articles/fcp) by reducing [Total Blocking Time (TBD)](https://web.dev/articles/tbt), which can also lower [Interaction to Next Paint (INP)](https://web.dev/articles/inp). This is why the [Chrome team has encouraged](https://web.dev/articles/rendering-on-the-web) developers to consider static or server-side render over a full client-side approach to achieve the best possible performance.
+
+There are tradeoffs to using a server, and it is not always the best option for every page. Generating pages on the server incurs additional cost and takes time to generate which can increase [Time to First Byte (TTFB)](https://web.dev/articles/ttfb). The best performing apps are able to pick the right rendering strategy on a per-page basis, based on the tradeoffs of each strategy.
+
+Frameworks provide the option to use a server on any page if you want to, but do not force you to use a server. This allows you to pick the right rendering strategy for each page in your app.
+
+#### What About Server Components {/*server-components*/}
+
+The frameworks we recommend also include support for React Server Components.
+
+Server Components help solve these problems by moving routing and data fetching to the server, and allowing code splitting to be done for client components based on the data you render, instead of just the route rendered, and reducing the amount of JavaScript shipped for the best possible [loading sequence](https://www.patterns.dev/vanilla/loading-sequence).
+
+Server Components do not require a server. They can be run at build time on your CI server to create a static-site generated app (SSG) app, at runtime on a web server for a server-side rendered (SSR) app.
+
+See [Introducing zero-bundle size React Server Components](/blog/2020/12/21/data-fetching-with-react-server-components) and [the docs](/reference/rsc/server-components) for more info.
+
+
+
+
+
+#### Server Rendering is not just for SEO {/*server-rendering-is-not-just-for-seo*/}
+
+A common misunderstanding is that server rendering is only for [SEO](https://developer.mozilla.org/en-US/docs/Glossary/SEO).
+
+While server rendering can improve SEO, it also improves performance by reducing the amount of JavaScript the user needs to download and parse before they can see the content on the screen.
+
+This is why the Chrome team [has encouraged](https://web.dev/articles/rendering-on-the-web) developers to consider static or server-side render over a full client-side approach to achieve the best possible performance.
+
+
+
+---
+
+_Thank you to [Dan Abramov](https://bsky.app/profile/danabra.mov) for creating Create React App, and [Joe Haddad](https://github.com/Timer), [Ian Schmitz](https://github.com/ianschmitz), [Brody McKee](https://github.com/mrmckeb), and [many others](https://github.com/facebook/create-react-app/graphs/contributors) for maintaining Create React App over the years. Thank you to [Brooks Lybrand](https://bsky.app/profile/brookslybrand.bsky.social), [Dan Abramov](https://bsky.app/profile/danabra.mov), [Devon Govett](https://bsky.app/profile/devongovett.bsky.social), [Eli White](https://x.com/Eli_White), [Jack Herrington](https://bsky.app/profile/jherr.dev), [Joe Savona](https://x.com/en_JS), [Lauren Tan](https://bsky.app/profile/no.lol), [Lee Robinson](https://x.com/leeerob), [Mark Erikson](https://bsky.app/profile/acemarke.dev), [Ryan Florence](https://x.com/ryanflorence), [Sophie Alpert](https://bsky.app/profile/sophiebits.com), [Tanner Linsley](https://bsky.app/profile/tannerlinsley.com), and [Theo Browne](https://x.com/theo) for reviewing and providing feedback on this post._
+
diff --git a/src/content/blog/index.md b/src/content/blog/index.md
index cc50b83c0..f7bbe76f3 100644
--- a/src/content/blog/index.md
+++ b/src/content/blog/index.md
@@ -4,12 +4,20 @@ 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.
+
+
+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 ...
diff --git a/src/content/community/conferences.md b/src/content/community/conferences.md
index dd9dd2510..46636d4c9 100644
--- a/src/content/community/conferences.md
+++ b/src/content/community/conferences.md
@@ -40,6 +40,11 @@ June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event)
[Website](https://reactsummit.com/) - [Twitter](https://x.com/reactsummit)
+### React Nexus 2025 {/*react-nexus-2025*/}
+July 03 - 05, 2025. In-person in Bangalore, India
+
+[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)
+
### React Universe Conf 2025 {/*react-universe-conf-2025*/}
September 2-4, 2025. Wrocław, Poland.
diff --git a/src/content/community/meetups.md b/src/content/community/meetups.md
index 14097aa4d..906c170de 100644
--- a/src/content/community/meetups.md
+++ b/src/content/community/meetups.md
@@ -57,6 +57,9 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet
* [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*/}
* [Lille](https://www.meetup.com/ReactBeerLille/)
* [Paris](https://www.meetup.com/ReactJS-Paris/)
@@ -136,6 +139,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/)
+## Sri Lanka {/*sri-lanka*/}
+* [Colombo](https://www.javascriptcolombo.com/)
+
## Sweden {/*sweden*/}
* [Goteborg](https://www.meetup.com/ReactJS-Goteborg/)
* [Stockholm](https://www.meetup.com/Stockholm-ReactJS-Meetup/)
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/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md
new file mode 100644
index 000000000..e5b396c7e
--- /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'd 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/framework/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://v3.vitejs.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/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md
new file mode 100644
index 000000000..fc6c956d4
--- /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 Node.js or serverless hosting, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn't require a server. Vercel additionally provides opt-in paid cloud services.
+
+### 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 built 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/installation.md b/src/content/learn/installation.md
index 1154a258f..5c00122d7 100644
--- a/src/content/learn/installation.md
+++ b/src/content/learn/installation.md
@@ -8,15 +8,6 @@ React è stato progettato sin dal principio per essere adottato gradualmente. A
-
-
-* [Come avviare un nuovo progetto React](/learn/start-a-new-react-project)
-* [Come aggiungere React ad un progetto esistente](/learn/add-react-to-an-existing-project)
-* [Come configurare il tuo editor](/learn/editor-setup)
-* [Come installare i React Developer Tools](/learn/react-developer-tools)
-
-
-
## Prova React {/*try-react*/}
Non devi installare nulla se vuoi divertirti con React. Prova a modificare questa sandbox!
@@ -39,14 +30,28 @@ Puoi modificarla direttamente o aprirla in un nuovo tab premendo il bottone "For
La maggioranza delle pagine della documentazione di React contengono sandboxes come questa. Al di fuori della documentazione, esistono alcune sandboxes online che supportano React: ad esempio, [CodeSandbox](https://codesandbox.io/s/new), [StackBlitz](https://stackblitz.com/fork/react), o [CodePen.](https://codepen.io/pen?template=QWYVwWN)
-### Prova React localmente {/*try-react-locally*/}
+Per provare React localmente sul tuo computer, [scarica questa pagina HTML.](https://gist.githubusercontent.com/gaearon/0275b1e1518599bbeafcde4722e79ed1/raw/db72dcbf3384ee1708c4a07d3be79860db04bff0/example.html) Aprila nel tuo editor e nel tuo browser!
-Per provare React localmente sul suo computer, [scarica questa pagina HTML.](https://gist.githubusercontent.com/gaearon/0275b1e1518599bbeafcde4722e79ed1/raw/db72dcbf3384ee1708c4a07d3be79860db04bff0/example.html) Aprila nel tuo editor e nel tuo browser!
+## Creare un'App React {/*creating-a-react-app*/}
-## Inizia un nuovo progetto React {/*start-a-new-react-project*/}
+Se vuoi iniziare una nuova app React, puoi [creare un'app React](/learn/creating-a-react-app) utilizzando un framework consigliato.
-Se desideri creare un'app o un sito web completamente con React, [inizia un nuovo progetto React.](/learn/start-a-new-react-project)
+## Costruire un'App React da zero {/*build-a-react-app-from-scratch*/}
+
+Se un framework non è adatto al tuo progetto, preferisci costruire il tuo framework, o vuoi semplicemente imparare le basi di un'app React puoi [costruire un'app React da zero](/learn/build-a-react-app-from-scratch).
## Aggiungi React ad un progetto esistente {/*add-react-to-an-existing-project*/}
-Se desideri provare ad utilizzare React nella tua app o in un sito web esistente, [aggiungi React ad un progetto esistente.](/learn/add-react-to-an-existing-project)
+Se vuoi provare ad utilizzare React nella tua app esistente o in un sito web, puoi [aggiungere React a un progetto esistente.](/learn/add-react-to-an-existing-project)
+
+
+
+#### Dovrei usare Create React App? {/*should-i-use-create-react-app*/}
+
+No. Create React App è stato deprecato. Per maggiori informazioni, consulta [Il sunsetting di Create React App](/blog/2025/02/14/sunsetting-create-react-app).
+
+
+
+## Prossimi passi {/*next-steps*/}
+
+Vai alla guida [Quick Start](/learn) per un tour dei più importanti concetti di React che incontrerai ogni giorno.
diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md
index e366ea7cc..2053f936b 100644
--- a/src/content/learn/manipulating-the-dom-with-refs.md
+++ b/src/content/learn/manipulating-the-dom-with-refs.md
@@ -647,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.
@@ -1049,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`.
@@ -1134,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 27d321afd..ed2ffb932 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}
-
+
);
}
```
-Questo dice a React: "se un qualsiasi componente all'interno di questa `` richiede `LevelContext`, fornisci loro questo `level`." Il componente utilizzerà il valore del `` più vicino nell'albero della UI sopra di esso.
+Questo dice a React: "se un qualsiasi componente all'interno di questa `` richiede `LevelContext`, fornisci loro questo `level`." Il componente utilizzerà il valore del `` più vicino nell'albero della UI sopra di esso.
@@ -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);
È lo stesso risultato del codice originale, ma non hai dovuto passare la prop `level` a ciascun componente `Heading`! Invece, questo "capisce" il suo livello d'intestazione interrogando il `Section` più vicino sopra di esso:
1. Passi la prop `level` a ``.
-2. `Section` avvolge i suoi figli in ``.
+2. `Section` avvolge i suoi figli in ``.
3. `Heading` richiede il valore più vicino di `LevelContext` sopra di sé con `useContext(LevelContext)`.
## Usare e fornire un context dallo stesso componente {/*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 generale, se alcune informazioni sono necessarie da componenti distanti in di
* Per passare il context:
1. Crealo ed esportalo con `export const MyContext = createContext(defaultValue)`.
2. Passalo all'Hook `useContext(MyContext)` per leggerlo in qualsiasi componente figlio, indipendentemente da quando in profondità sia.
- 3. Avvolgi i figli in `` per fornirlo da un genitore.
+ 3. Avvolgi i figli in `` per fornirlo da un genitore.
* Il context attraversa qualsiasi componente intermedio.
* Il context ti consente di scrivere componenti che "si adattano all'ambiente circostante".
* Prima di utilizzare il context, prova a passare le props o passare il JSX come `children`.
@@ -963,27 +963,27 @@ export const places = [{
description: 'The tradition of choosing bright colors for houses began in the late 20th century.',
imageId: 'K9HVAGH'
}, {
- id: 1,
+ id: 1,
name: 'Rainbow Village in Taichung, Taiwan',
description: 'To save the houses from demolition, Huang Yung-Fu, a local resident, painted all 1,200 of them in 1924.',
imageId: '9EAYZrt'
}, {
- id: 2,
+ id: 2,
name: 'Macromural de Pachuca, Mexico',
description: 'One of the largest murals in the world covering homes in a hillside neighborhood.',
imageId: 'DgXHVwu'
}, {
- id: 3,
+ id: 3,
name: 'Selarón Staircase in Rio de Janeiro, Brazil',
description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people."',
imageId: 'aeO3rpI'
}, {
- id: 4,
+ id: 4,
name: 'Burano, Italy',
description: 'The houses are painted following a specific color system dating back to 16th century.',
imageId: 'kxsph5C'
}, {
- id: 5,
+ id: 5,
name: 'Chefchaouen, Marocco',
description: 'There are a few theories on why the houses are painted blue, including that the color repels mosquitos or that it symbolizes sky and heaven.',
imageId: 'rTqKo46'
@@ -1007,9 +1007,9 @@ export function getImageUrl(place) {
```css
ul { list-style-type: none; padding: 0px 10px; }
-li {
- margin-bottom: 10px;
- display: grid;
+li {
+ margin-bottom: 10px;
+ display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
align-items: center;
@@ -1022,7 +1022,7 @@ li {
Rimuovi la prop `imageSize` da tutti i componenti.
-Crea ed esporta `ImageSizeContext` da `Context.js`. Quindi avvolgi `List` in `` per passare il valore in basso, e utilizza `useContext(ImageSizeContext)` per leggerlo in `PlaceImage`:
+Crea ed esporta `ImageSizeContext` da `Context.js`. Quindi avvolgi `List` in `` per passare il valore in basso, e utilizza `useContext(ImageSizeContext)` per leggerlo in `PlaceImage`:
@@ -1036,7 +1036,7 @@ export default function App() {
const [isLarge, setIsLarge] = useState(false);
const imageSize = isLarge ? 150 : 100;
return (
-
-
+
)
}
@@ -1102,27 +1102,27 @@ export const places = [{
description: 'The tradition of choosing bright colors for houses began in the late 20th century.',
imageId: 'K9HVAGH'
}, {
- id: 1,
+ id: 1,
name: 'Rainbow Village in Taichung, Taiwan',
description: 'To save the houses from demolition, Huang Yung-Fu, a local resident, painted all 1,200 of them in 1924.',
imageId: '9EAYZrt'
}, {
- id: 2,
+ id: 2,
name: 'Macromural de Pachuca, Mexico',
description: 'One of the largest murals in the world covering homes in a hillside neighborhood.',
imageId: 'DgXHVwu'
}, {
- id: 3,
+ id: 3,
name: 'Selarón Staircase in Rio de Janeiro, Brazil',
description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people".',
imageId: 'aeO3rpI'
}, {
- id: 4,
+ id: 4,
name: 'Burano, Italy',
description: 'The houses are painted following a specific color system dating back to 16th century.',
imageId: 'kxsph5C'
}, {
- id: 5,
+ id: 5,
name: 'Chefchaouen, Marocco',
description: 'There are a few theories on why the houses are painted blue, including that the color repels mosquitos or that it symbolizes sky and heaven.',
imageId: 'rTqKo46'
@@ -1146,9 +1146,9 @@ export function getImageUrl(place) {
```css
ul { list-style-type: none; padding: 0px 10px; }
-li {
- margin-bottom: 10px;
- display: grid;
+li {
+ margin-bottom: 10px;
+ display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
align-items: center;
diff --git a/src/content/learn/react-compiler.md b/src/content/learn/react-compiler.md
index 0ae499472..7c46673e7 100644
--- a/src/content/learn/react-compiler.md
+++ b/src/content/learn/react-compiler.md
@@ -311,7 +311,7 @@ export default defineConfig({
### Webpack {/*usage-with-webpack*/}
-A community Webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).
+A community webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).
### Expo {/*usage-with-expo*/}
diff --git a/src/content/learn/render-and-commit.md b/src/content/learn/render-and-commit.md
index 792e7f45e..f6e91a7d7 100644
--- a/src/content/learn/render-and-commit.md
+++ b/src/content/learn/render-and-commit.md
@@ -65,12 +65,12 @@ export default function Image() {
Prova a commentare la chiamata `root.render()` e vedrai il componente scomparire!
-### Renderizzare nuovamente quando lo state viene aggiornato{/*re-renders-when-state-updates*/}
+### Renderizzare nuovamente quando lo state viene aggiornato {/*re-renders-when-state-updates*/}
Una volta che il componente è inizialmente renderizzato, è possibile avviare ulteriori renderizzazioni aggiornando il suo state con la [funzione `set`.](/reference/react/useState#setstate) Aggiornare lo state del componente mette automaticamente in coda una renderizzazione (puoi immaginarlo come un ospite del ristorante che ordina tè, dessert e ogni sorta di cosa dopo aver effettuato il primo ordine, a seconda della sua sete o fame)
-
+
@@ -84,7 +84,7 @@ Dopo aver avviato la renderizzazione, React richiama i tuoi componenti per capir
Questo processo è ricorsivo: se il componente aggiornato restituisce un altro componente, React renderizzerà _quel_ componente successivamente, e se quel componente restituisce a sua volta qualcosa, renderizzerà _quel_ componente successivamente, e cosi via. Il processo continua finché non ci sono più componenti annidati e React sa esattamente cosa mostrare a schermo.
-Nell'esempio seguente, React chiamerà `Gallery()` e `Image()` diverse volte:
+Nell'esempio seguente, React chiamerà `Gallery()` e `Image()` diverse volte:
@@ -124,7 +124,7 @@ img { margin: 0 10px 10px 0; }
-* **Durante la renderizzazione iniziale,** React [creerà i nodi del DOM](https://developer.mozilla.org/docs/Web/API/Document/createElement) per ``, `
`, e tre tag ``.
+* **Durante la renderizzazione iniziale,** React [creerà i nodi del DOM](https://developer.mozilla.org/docs/Web/API/Document/createElement) per ``, `
`, e tre tag ``.
* **Durante una renderizzazione successiva,** React calcolerà quali delle sue proprietà, se presenti, sono cambiate rispetto la renderizzazione precedente. Tuttavia, non farà nulla con queste informazioni fino alla prossima fase, la fase di commit.
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 a4cda97d9..000000000
--- a/src/content/learn/start-a-new-react-project.md
+++ /dev/null
@@ -1,130 +0,0 @@
----
-title: Avviare un Nuovo Progetto React
----
-
-
-
-Se vuoi costruire una nuova app o un nuovo sito web interamente con React, ti consigliamo di scegliere uno dei framework basati su React piú popolari nella comunità.
-
-
-
-
-Puoi usare React senza un framework, tuttavia abbiamo trovato che la maggior parte delle app e dei siti alla fine costruiscono soluzioni per problemi comuni come la suddivisione del codice, il routing, il recupero dei dati e la generazione di HTML. Questi problemi sono comuni a tutte le librerie di interfaccia utente, non solo a React.
-
-Cominciando con un framework, puoi iniziare ad utilizzare React rapidamente ed evitare di costruire il tuo framework in seguito.
-
-
-
-#### Posso utilizzare React senza un framework? {/*can-i-use-react-without-a-framework*/}
-
-Puoi sicuramente usare React senza un framework: è così che [useresti React per una parte della tua pagina.](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page) **Tuttavia, se stai creando una nuova app o un sito completamente con React, ti consigliamo di utilizzare un framework.**
-
-Ecco perché.
-
-Anche se all'inizio potresti non aver bisogno di routing o di recupero dati, è probabile che tu voglia aggiungere alcune librerie per queste funzionalità. Con ogni nuova funzionalità, il tuo bundle JavaScript cresce e potresti dover capire come suddividere il codice per ogni singola route in modo individuale. Con esigenze di recupero dati più complesse, è probabile che incontri situazioni in cui la rete tra server e client crea un effetto di cascata che rende la tua app molto lenta. Siccome il tuo pubblico include più utenti con condizioni di rete scadenti o dispositivi di fascia bassa, potresti dover generare HTML dai tuoi componenti per mostrare il contenuto in anticipo, sia lato server che durante la fase di build. Modificare la configurazione per eseguire parte del tuo codice sul server o durante la fase di build può essere molto complicato.
-
-**Questi problemi non sono specifici di React. Questo è il motivo per cui Svelte ha SvelteKit, Vue ha Nuxt e così via.** Per risolvere questi problemi da soli, sarà necessario integrare il tuo bundler con il tuo router e con la tua libreria di recupero dati. Non è difficile far funzionare una configurazione iniziale, ma ci sono molte sottigliezze coinvolte nel creare un'applicazione che si carichi rapidamente anche crescendo nel tempo. Vorrai inviare solo il minimo necessario di codice dell'applicazione, ma farlo in un unico collegamento client-server, in parallelo con i dati richiesti per la pagina. Probabilmente vorrai che la pagina sia interattiva prima ancora che il tuo codice JavaScript venga eseguito, per supportare il miglioramento progressivo. Potresti voler generare una cartella di file HTML completamente statici per le tue pagine di marketing che possono essere ospitate ovunque e funzionare ancora con JavaScript disabilitato. Costruire queste capacità da soli richiede parecchio lavoro.
-
-**I framework React presenti in questa pagina risolvono questi problemi di default, senza alcun lavoro aggiuntivo da parte tua.** Ti permettono di iniziare con una configurazione leggera e poi scalare la tua app in base alle tue esigenze. Ogni framework React ha una comunità, quindi trovare risposte alle domande e aggiornare gli strumenti è più facile. Inoltre, i framework forniscono una struttura al tuo codice, aiutando te stesso e gli altri a mantenere il contesto e le competenze tra diversi progetti. Al contrario, con una configurazione personalizzata è più facile rimanere bloccati con versioni di dipendenze non supportate, e alla fine finirai per creare il tuo framework, anche se in modo meno strutturato e senza una comunità o un percorso di aggiornamento (e se è simile a quelli che abbiamo creato in passato, potrebbe essere progettato in modo più casuale).
-
-Se la tua app ha vincoli insoliti che non sono soddisfatti da questi framework, oppure preferisci risolvere questi problemi da solo, puoi creare la tua configurazione personalizzata con React. Scarica `react` e `react-dom` da npm, configura il tuo processo di build personalizzato con un bundler come [Vite](https://vite.dev/) o [Parcel](https://parceljs.org/) e aggiungi altri strumenti di cui hai bisogno per il routing, la generazione statica o il rendering lato server e altro ancora.
-
-
-
-## Framework React di qualità professionale {/*production-grade-react-frameworks*/}
-
-Questi framework supportano tutte le funzionalità di cui hai bisogno per distribuire e scalare la tua app in produzione e stanno lavorando per supportare la nostra [visione di architettura full-stack](#which-features-make-up-the-react-teams-full-stack-architecture-vision). Tutti i framework che consigliamo sono open source con comunità attive per il supporto e possono essere distribuiti sul tuo server o su un provider di hosting. Se sei un autore di framework interessato a essere incluso in questa lista, [faccelo sapere](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*/}
-
-**[Il Router di Pagine di Next.js](https://nextjs.org/) è un framework React full-stack.** È versatile e ti consente di creare app React di qualsiasi dimensione, da un blog principalmente statico a un'applicazione dinamica complessa. Per creare un nuovo progetto Next.js, esegui il seguente comando nel tuo terminale:
-
-
-npx create-next-app@latest
-
-
-Se sei nuovo in Next.js, dai un'occhiata al [corso per imparare Next.js.](https://nextjs.org/learn)
-
-Next.js è mantenuto da [Vercel](https://vercel.com/). Puoi [distribuire un'app Next.js](https://nextjs.org/docs/app/building-your-application/deploying) su qualsiasi hosting Node.js o serverless, o sul tuo server personale. [Le app Next.js completamente statiche](https://nextjs.org/docs/advanced-features/static-html-export) possono essere distribuite su qualsiasi hosting statico.
-
-### Remix {/*remix*/}
-
-**[Remix](https://remix.run/) è un framework React full-stack con routing nidificato.** Ti consente di suddividere la tua app in parti nidificate che possono caricare dati in parallelo e aggiornarsi in risposta alle azioni dell'utente. Per creare un nuovo progetto Remix, esegui il seguente comando:
-
-
-npx create-remix
-
-
-Se sei nuovo in Remix, dai un'occhiata al [blog tutorial](https://remix.run/docs/en/main/tutorials/blog) (breve) e al [app tutorial](https://remix.run/docs/en/main/tutorials/jokes) (lungo).
-
-Remix è mantenuto da [Shopify](https://www.shopify.com/). Quando crei un progetto Remix, devi [scegliere il tuo target di distribuzione](https://remix.run/docs/en/main/guides/deployment). Puoi distribuire un'app Remix su qualsiasi hosting Node.js o serverless utilizzando o scrivendo un [adattatore](https://remix.run/docs/en/main/other-api/adapter).
-
-### Gatsby {/*gatsby*/}
-
-**[Gatsby](https://www.gatsbyjs.com/) è un framework React per siti web CMS veloci.** Il suo ricco ecosistema di plugin e il suo livello di dati GraphQL semplificano l'integrazione di contenuti, API e servizi in un unico sito web. Per creare un nuovo progetto Gatsby, esegui il seguente comando:
-
-
-npx create-gatsby
-
-
-Se sei nuovo in Gatsby, dai un'occhiata al [Gatsby tutorial.](https://www.gatsbyjs.com/docs/tutorial/)
-
-Gatsby è mantenuto da [Netlify](https://www.netlify.com/). Puoi [distribuire un sito Gatsby completamente statico](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting) su qualsiasi hosting statico. Se opti per l'utilizzo di funzionalità server-side, assicurati che il tuo provider di hosting supporti tali funzionalità per Gatsby.
-
-### Expo (for native apps) {/*expo*/}
-
-**[Expo](https://expo.dev/) è un framework per React che ti consente di creare app universali per Android, iOS e web con interfacce utente veramente native.** Fornisce un SDK per [React Native](https://reactnative.dev/) che semplifica l'utilizzo delle parti native. Per creare un nuovo progetto Expo, esegui il seguente comando:
-
-
-npx create-expo-app
-
-
-Se sei nuovo in Expo, puoi seguire [Expo tutorial](https://docs.expo.dev/tutorial/introduction/).
-
-Expo è mantenuto da [Expo (l'azienda)](https://expo.dev/about). La creazione di app con Expo è gratuita e puoi inviarle agli app store di Google e Apple senza restrizioni. Expo fornisce inoltre servizi cloud a pagamento opzionali.
-
-## Framework React all'avanguardia {/*bleeding-edge-react-frameworks*/}
-
-Come abbiamo esplorato come migliorare continuamente React, abbiamo realizzato che integrare React in modo più stretto con i framework (in particolare con il routing, il bundling e le tecnologie server) è la nostra più grande opportunità per aiutare gli utenti di React a costruire app migliori. Il team di Next.js ha accettato di collaborare con noi nella ricerca, nello sviluppo, nell'integrazione e nei test di funzionalità di React all'avanguardia, indipendenti dai framework, come [React Server Components.](/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components)
-
-Queste funzionalità stanno diventando sempre più vicine alla prontezza per la produzione ogni giorno, e abbiamo avviato discussioni con altri sviluppatori di bundler e framework per integrarle. La nostra speranza è che tra un anno o due, tutti i framework elencati in questa pagina avranno il pieno supporto per queste funzionalità. (Se sei un autore di framework interessato a collaborare con noi per sperimentare con queste funzionalità, ti preghiamo di farcelo sapere!)
-
-### Next.js (App Router) {/*nextjs-app-router*/}
-
-**[Il router dell'app di Next.js's](https://beta.nextjs.org/docs/getting-started) è una ridisegnazione delle API di Next.js che mira a realizzare la visione di architettura full-stack del team di React.** Consente di recuperare dati in componenti asincroni che vengono eseguiti sul server o addirittura durante la fase di build.
-
-Next.js è mantenuto da [Vercel](https://vercel.com/). Puoi [distribuire un'app Next.js](https://nextjs.org/docs/deployment) su qualsiasi hosting Node.js o serverless, o sul tuo server. Next.js supporta anche [l'esportazione statica](https://beta.nextjs.org/docs/configuring/static-export) che non richiede un server.
-
-
-
-#### Quali caratteristiche compongono la visione di architettura full-stack del team di React? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/}
-
-Il bundler del router dell'app di Next.js implementa completamente la specifica ufficiale dei [React Server Components](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). Questo consente di mescolare componenti generati a tempo di build, componenti esclusivamente server-side e componenti interattivi all'interno di un singolo albero di React.
-
-Ad esempio, è possibile scrivere un componente React esclusivamente server-side come una funzione `async` che legge da un database o da un file. Successivamente, è possibile passare i dati ai componenti interattivi:
-
-```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 ;
-}
-```
-
-Il router dell'app di Next.js integra anche il [recupero dei dati con Suspense.](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). Questo consente di specificare uno stato di caricamento (come un segnaposto scheletro) per diverse parti dell'interfaccia utente direttamente nell'albero di React:
-
-```js
-}>
-
-
-```
-
-Server Components e Suspense sono funzionalità di React che possono essere adottate a livello di framework. Al momento, il router dell'app di Next.js è l'implementazione più completa di queste funzionalità tra i vari framework. Il team di React sta anche lavorando con gli sviluppatori di bundler per rendere più semplice l'implementazione di queste funzionalità nella prossima generazione di framework.
-
-
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index c62ba1985..39598ea8c 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -40,14 +40,14 @@ export default function Gallery() {
Next
- {sculpture.name}
+ {sculpture.name}
by {sculpture.artist}
-
+
({index + 1} of {sculptureList.length})
-
@@ -64,7 +64,7 @@ export const sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -220,14 +220,14 @@ export default function Gallery() {
Next
- {sculpture.name}
+ {sculpture.name}
by {sculpture.artist}
-
+
({index + 1} of {sculptureList.length})
-
@@ -244,7 +244,7 @@ export const sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -341,7 +341,7 @@ Lo State è solo una di queste funzionalità, ma incontrerai gli altri Hook più
-**Gli Hook (funzioni che iniziano per `use`) possono essere chiamati solo al livello superiore del tuo componente o [dei tuoi Hook.](/learn/reusing-logic-with-custom-hooks)** Non è possibile chiamare gli Hook all'interno di condizioni, cicli o altre funzioni nidificate. Gli Hook sono funzioni, ma è di aiuto considerarli come dichiarazioni incondizionate sulle necessità del tuo componente. "Usi" le funzionalità di React in cima al tuo componente in modo simile a come "importi" i moduli in cima al tuo file.
+**Gli Hook (funzioni che iniziano per `use`) possono essere chiamati solo al livello superiore del tuo componente o [dei tuoi Hook.](/learn/reusing-logic-with-custom-hooks)** Non è possibile chiamare gli Hook all'interno di condizioni, cicli o altre funzioni nidificate. Gli Hook sono funzioni, ma è di aiuto considerarli come dichiarazioni incondizionate sulle necessità del tuo componente. "Usi" le funzionalità di React in cima al tuo componente in modo simile a come "importi" i moduli in cima al tuo file.
@@ -408,18 +408,18 @@ export default function Gallery() {
Next
- {sculpture.name}
+ {sculpture.name}
by {sculpture.artist}
-
+
({index + 1} of {sculptureList.length})
{showMore &&
{sculpture.description}
}
-
>
@@ -433,7 +433,7 @@ export const sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -629,7 +629,7 @@ let sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -773,18 +773,18 @@ export default function Gallery() {
Next
- {sculpture.name}
+ {sculpture.name}
by {sculpture.artist}
-
+
({index + 1} of {sculptureList.length})
{showMore &&
{sculpture.description}
}
-
@@ -798,7 +798,7 @@ export const sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -944,18 +944,18 @@ export default function Gallery() {
Next
- {sculpture.name}
+ {sculpture.name}
by {sculpture.artist}
-
+
({index + 1} of {sculptureList.length})
{showMore &&
{sculpture.description}
}
-
>
@@ -969,7 +969,7 @@ export const sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -1106,18 +1106,18 @@ export default function Gallery() {
Next
- {sculpture.name}
+ {sculpture.name}
by {sculpture.artist}
-
+
({index + 1} of {sculptureList.length})
{showMore &&
{sculpture.description}
}
-
>
@@ -1131,7 +1131,7 @@ export const sculptureList = [{
artist: 'Marta Colvin Andrade',
description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
name: 'Floralis Genérica',
artist: 'Eduardo Catalano',
@@ -1266,7 +1266,7 @@ export default function Form() {
}
```
-```css
+```css
h1 { margin-top: 10px; }
```
@@ -1317,7 +1317,7 @@ export default function Form() {
}
```
-```css
+```css
h1 { margin-top: 10px; }
```
@@ -1452,7 +1452,7 @@ Se il tuo linter è [configurato per React](/learn/editor-setup#linting), dovres
#### Rimuovi lo state superfluo {/*remove-unnecessary-state*/}
-Quando viene cliccato il pulsante, questo esempio dovrebbe chiedere il nome dell'utente e poi visualizzare un alert di saluto. Hai provato a utilizzare lo state per conservare il nome, ma per qualche ragione mostra sempre "Hello, !".
+Quando viene cliccato il pulsante, questo esempio dovrebbe chiedere il nome dell'utente e poi visualizzare un alert di saluto. Hai provato a utilizzare lo state per conservare il nome, ma per qualche ragione la prima volta mostra "Hello, !", e poi "Hello, [nome]!" con l'input precedente ogni volta dopo.
Per correggere questo codice, rimuovi la variabile state superflua. (Discuteremo del [perché questo non ha funzionato](/learn/state-as-a-snapshot) in seguito.)
diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md
index 54e7a7f1d..0a3933949 100644
--- a/src/content/reference/react-dom/client/createRoot.md
+++ b/src/content/reference/react-dom/client/createRoot.md
@@ -344,775 +344,127 @@ export default function App({counter}) {
It is uncommon to call `render` multiple times. Usually, your components will [update state](/reference/react/useState) 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 uncaught errors to the console. To implement your own error reporting, you can provide the optional `onUncaughtError` root option:
+By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`:
-```js [[1, 6, "onUncaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack"]]
-import { createRoot } from 'react-dom/client';
-
-const root = createRoot(
- document.getElementById('root'),
- {
- onUncaughtError: (error, errorInfo) => {
- console.error(
- 'Uncaught error',
- error,
- errorInfo.componentStack
- );
- }
- }
-);
-root.render();
-```
-
-The onUncaughtError 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:
-
-
-
-```html public/index.html hidden
-
-
-
- My app
-
-
-
-
- );
-}
-```
-
-
-
-
-### Displaying Error Boundary errors {/*displaying-error-boundary-errors*/}
-
-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 public/index.html hidden
-
-
-
- My app
-
-
-
-
-
-
-
-
-
-
-
-
This error occurred at:
-
-
Call stack:
-
-
-
Caused by:
-
-
-
-
-
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;
+```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);
}
-.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");
+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 { 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";
-
-export default function App() {
- const [error, setError] = useState(null);
-
- function handleUnknown() {
- setError("unknown");
- }
+import { Component, useState } from "react";
- 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": "19.0.0-rc-3edc000d-20240926",
- "react-dom": "19.0.0-rc-3edc000d-20240926",
- "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 public/index.html hidden
-
-
-
- My app
-
-
-
-
- );
-}
-
-function Throw({error}) {
- // Simulate an external value changing during concurrent render.
- errorThrown = true;
- foo.bar = 'baz';
-}
-```
-
-```json package.json hidden
-{
- "dependencies": {
- "react": "19.0.0-rc-3edc000d-20240926",
- "react-dom": "19.0.0-rc-3edc000d-20240926",
- "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 b1eeca30c..99190b03a 100644
--- a/src/content/reference/react-dom/client/hydrateRoot.md
+++ b/src/content/reference/react-dom/client/hydrateRoot.md
@@ -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,554 +374,124 @@ 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 uncaught errors to the console. To implement your own error reporting, you can provide the optional `onUncaughtError` root option:
+By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`:
-```js [[1, 7, "onUncaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack"]]
-import { hydrateRoot } from 'react-dom/client';
+```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]]
+import { hydrateRoot } from "react-dom/client";
+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 public/index.html hidden
-
-
-
- My app
-
-
-
-
-
-
-
-
-
-
-
-
This error occurred at:
-
-
Call stack:
-
-
-
Caused by:
-
-
-
-
-
This error is not dismissible.
-
-
-
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;
+```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);
}
-.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 = '';
+export function onCaughtErrorProd(error, errorInfo) {
+ if (error.message !== "Known error") {
+ reportError({ type: "Caught", error, errorInfo });
}
-
- // 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 onUncaughtErrorProd(error, errorInfo) {
+ reportError({ type: "Uncaught", error, errorInfo });
}
-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';
+import { Component, useState } from "react";
-export default function App() {
- const [throwError, setThrowError] = useState(false);
-
- if (throwError) {
- foo.bar = 'baz';
- }
-
- return (
-
- This error shows the error dialog:
-
-
- );
+function Boom() {
+ foo.bar = "baz";
}
-```
-
-
-
-### Displaying Error Boundary errors {/*displaying-error-boundary-errors*/}
-
-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):
+class ErrorBoundary extends Component {
+ state = { hasError: false };
-```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
- );
- }
+ static getDerivedStateFromError(error) {
+ return { hasError: true };
}
-);
-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 public/index.html hidden
-
-
-
- My app
-
-
-
-
-
-
-
-
-
-
-
-
This error occurred at:
-
-
Call stack:
-
-
-
Caused by:
-
-
-
-
-
This error is not dismissible.
-
-
-
This error will not show the error dialog:This error will show the error dialog:
;
}
+ 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": "19.0.0-rc-3edc000d-20240926",
- "react-dom": "19.0.0-rc-3edc000d-20240926",
- "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 public/index.html hidden
@@ -930,226 +500,12 @@ You can use the `onRecoverableError` root option to display error dialogs for hy
-