Skip to content

Commit

Permalink
merging all conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
react-translations-bot committed Oct 21, 2024
2 parents ed02cf1 + 9467bc5 commit 16c6566
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 117 deletions.
180 changes: 63 additions & 117 deletions src/content/learn/react-compiler.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ title: React Compiler
{/* FIXME:L10N */}

<Intro>
This page will give you an introduction to the new experimental React Compiler and how to try it out successfully.
This page will give you an introduction to React Compiler and how to try it out successfully.
</Intro>

<Wip>
Expand All @@ -21,12 +21,28 @@ These docs are still a work in progress. More documentation is available in the
</YouWillLearn>

<Note>
React Compiler is a new experimental compiler that we've open sourced to get early feedback from the community. It still has rough edges and is not yet fully ready for production.
React Compiler is a new compiler currently in Beta, that we've open sourced to get early feedback from the community. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you’ve followed the [Rules of React](/reference/rules).

The latest Beta release can be found with the `@beta` tag, and daily experimental releases with `@experimental`.
</Note>

React Compiler is a new experimental compiler that we've open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it.
React Compiler is a new compiler that we've open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it.

The compiler also includes an [eslint plugin](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. **We strongly recommend everyone use the linter today.** The linter does not require that you have the compiler installed, so you can use it even if you are not ready to try out the compiler.

The compiler also includes an [eslint plugin](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. The plugin runs independently of the compiler and can be used even if you aren't using the compiler in your app. We recommend all React developers to use this eslint plugin to help improve the quality of your codebase.
The compiler is currently released as `beta`, and is available to try out on React 17+ apps and libraries. To install the Beta:

<TerminalBlock>
npm install -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta
</TerminalBlock>

Or, if you're using Yarn:

<TerminalBlock>
yarn add -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta
</TerminalBlock>

If you are not using React 19 yet, please see [the section below](#using-react-compiler-with-react-17-or-18) for further instructions.

### What does the compiler do? {/*what-does-the-compiler-do*/}

Expand Down Expand Up @@ -96,19 +112,9 @@ However, if `expensivelyProcessAReallyLargeArrayOfObjects` is truly an expensive
So if `expensivelyProcessAReallyLargeArrayOfObjects` was used in many different components, even if the same exact items were passed down, that expensive calculation would be run repeatedly. We recommend [profiling](https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive) first to see if it really is that expensive before making code more complicated.
</DeepDive>

### What does the compiler assume? {/*what-does-the-compiler-assume*/}

React Compiler assumes that your code:

1. Is valid, semantic JavaScript
2. Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) if using TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` or with optional-chaining `object.nullableProperty?.foo`
3. Follows the [Rules of React](https://react.dev/reference/rules)

React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler).

### Should I try out the compiler? {/*should-i-try-out-the-compiler*/}

Please note that the compiler is still experimental and has many rough edges. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules).
Please note that the compiler is still in Beta and has many rough edges. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules).

**You don't have to rush into using the compiler now. It's okay to wait until it reaches a stable release before adopting it.** However, we do appreciate trying it out in small experiments in your apps so that you can [provide feedback](#reporting-issues) to us to help make the compiler better.

Expand All @@ -121,7 +127,7 @@ In addition to these docs, we recommend checking the [React Compiler Working Gro
Prior to installing the compiler, you can first check to see if your codebase is compatible:

<TerminalBlock>
npx react-compiler-healthcheck@experimental
npx react-compiler-healthcheck@beta
</TerminalBlock>

This script will:
Expand All @@ -143,7 +149,7 @@ Found no usage of incompatible libraries.
React Compiler also powers an eslint plugin. The eslint plugin can be used **independently** of the compiler, meaning you can use the eslint plugin even if you don't use the compiler.

<TerminalBlock>
npm install eslint-plugin-react-compiler@experimental
npm install -D eslint-plugin-react-compiler@beta
</TerminalBlock>

Then, add it to your eslint config:
Expand Down Expand Up @@ -178,77 +184,75 @@ const ReactCompilerConfig = {
};
```

In rare cases, you can also configure the compiler to run in "opt-in" mode using the `compilationMode: "annotation"` option. This makes it so the compiler will only compile components and hooks annotated with a `"use memo"` directive. Please note that the `annotation` mode is a temporary one to aid early adopters, and that we don't intend for the `"use memo"` directive to be used for the long term.

```js {2,7}
const ReactCompilerConfig = {
compilationMode: "annotation",
};

// src/app.jsx
export default function App() {
"use memo";
// ...
}
```

When you have more confidence with rolling out the compiler, you can expand coverage to other directories as well and slowly roll it out to your whole app.

#### New projects {/*new-projects*/}

If you're starting a new project, you can enable the compiler on your entire codebase, which is the default behavior.

## Usage {/*installation*/}
### Using React Compiler with React 17 or 18 {/*using-react-compiler-with-react-17-or-18*/}

### Babel {/*usage-with-babel*/}
React Compiler works best with React 19 RC. If you are unable to upgrade, you can install the extra `react-compiler-runtime` package which will allow the compiled code to run on versions prior to 19. However, note that the minimum supported version is 17.

<TerminalBlock>
npm install babel-plugin-react-compiler@experimental
npm install react-compiler-runtime@beta
</TerminalBlock>

The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler.

After installing, add it to your Babel config. Please note that it's critical that the compiler run **first** in the pipeline:
You should also add the correct `target` to your compiler config, where `target` is the major version of React you are targeting:

```js {7}
```js {3}
// babel.config.js
const ReactCompilerConfig = { /* ... */ };
const ReactCompilerConfig = {
target: '18' // '17' | '18' | '19'
};

module.exports = function () {
return {
plugins: [
['babel-plugin-react-compiler', ReactCompilerConfig], // must run first!
// ...
['babel-plugin-react-compiler', ReactCompilerConfig],
],
};
};
```

`babel-plugin-react-compiler` should run first before other Babel plugins as the compiler requires the input source information for sound analysis.
### Using the compiler on libraries {/*using-the-compiler-on-libraries*/}

React Compiler works best with React 19 RC. If you are unable to upgrade, you can install the extra `react-compiler-runtime` package which will allow the compiled code to run on versions prior to 19. However, note that the minimum supported version is 17.
React Compiler can also be used to compile libraries. Because React Compiler needs to run on the original source code prior to any code transformations, it is not possible for an application's build pipeline to compile the libraries they use. Hence, our recommendation is for library maintainers to independently compile and test their libraries with the compiler, and ship compiled code to npm.

Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum [`target` and add `react-compiler-runtime` as a direct dependency](#using-react-compiler-with-react-17-or-18). The runtime package will use the correct implementation of APIs depending on the application's version, and polyfill the missing APIs if necessary.

Library code can often require more complex patterns and usage of escape hatches. For this reason, we recommend ensuring that you have sufficient testing in order to identify any issues that might arise from using the compiler on your library. If you identify any issues, you can always opt-out the specific components or hooks with the [`'use no memo'` directive](#something-is-not-working-after-compilation).

Similarly to apps, it is not necessary to fully compile 100% of your components or hooks to see benefits in your library. A good starting point might be to identify the most performance sensitive parts of your library and ensuring that they don't break the [Rules of React](/reference/rules), which you can use `eslint-plugin-react-compiler` to identify.

## Usage {/*installation*/}

### Babel {/*usage-with-babel*/}

<TerminalBlock>
npm install react-compiler-runtime@experimental
npm install babel-plugin-react-compiler@beta
</TerminalBlock>

You should also add the correct `target` to your compiler config, where `target` is the major version of React you are targeting:
The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler.

```js {3}
After installing, add it to your Babel config. Please note that it's critical that the compiler run **first** in the pipeline:

```js {7}
// babel.config.js
const ReactCompilerConfig = {
target: '18' // '17' | '18' | '19'
};
const ReactCompilerConfig = { /* ... */ };

module.exports = function () {
return {
plugins: [
['babel-plugin-react-compiler', ReactCompilerConfig],
['babel-plugin-react-compiler', ReactCompilerConfig], // must run first!
// ...
],
};
};
```

`babel-plugin-react-compiler` should run first before other Babel plugins as the compiler requires the input source information for sound analysis.

### Vite {/*usage-with-vite*/}

If you use Vite, you can add the plugin to vite-plugin-react:
Expand All @@ -275,36 +279,7 @@ export default defineConfig(() => {

### Next.js {/*usage-with-nextjs*/}

Next.js has an experimental configuration to enable the React Compiler. It automatically ensures Babel is set up with `babel-plugin-react-compiler`.

- Install Next.js canary, which uses React 19 Release Candidate
- Install `babel-plugin-react-compiler`

<TerminalBlock>
npm install next@canary babel-plugin-react-compiler@experimental
</TerminalBlock>

Then configure the experimental option in `next.config.js`:

```js {4,5,6}
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
reactCompiler: true,
},
};

module.exports = nextConfig;
```

Using the experimental option ensures support for the React Compiler in:

- App Router
- Pages Router
- Webpack (default)
- Turbopack (opt-in through `--turbo`)

Please refer to the [Next.js docs](https://nextjs.org/docs/canary/app/api-reference/next-config-js/reactCompiler) for more information.

### Remix {/*usage-with-remix*/}
Install `vite-plugin-babel`, and add the compiler's Babel plugin to it:
Expand Down Expand Up @@ -337,40 +312,7 @@ export default defineConfig({

### Webpack {/*usage-with-webpack*/}

You can create your own loader for React Compiler, like so:

```js
const ReactCompilerConfig = { /* ... */ };
const BabelPluginReactCompiler = require('babel-plugin-react-compiler');

function reactCompilerLoader(sourceCode, sourceMap) {
// ...
const result = transformSync(sourceCode, {
// ...
plugins: [
[BabelPluginReactCompiler, ReactCompilerConfig],
],
// ...
});

if (result === null) {
this.callback(
Error(
`Failed to transform "${options.filename}"`
)
);
return;
}

this.callback(
null,
result.code,
result.map === null ? undefined : result.map
);
}

module.exports = reactCompilerLoader;
```
A community Webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).

### Expo {/*usage-with-expo*/}

Expand All @@ -394,11 +336,15 @@ To report issues, please first create a minimal repro on the [React Compiler Pla

You can also provide feedback in the React Compiler Working Group by applying to be a member. Please see [the README for more details on joining](https://github.com/reactwg/react-compiler).

### `(0 , _c) is not a function` error {/*0--_c-is-not-a-function-error*/}
### What does the compiler assume? {/*what-does-the-compiler-assume*/}

React Compiler assumes that your code:

This occurs if you are not using React 19 RC and up. To fix this, [upgrade your app to React 19 RC](https://react.dev/blog/2024/04/25/react-19-upgrade-guide) first.
1. Is valid, semantic JavaScript.
2. Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) if using TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` or with optional-chaining `object.nullableProperty?.foo`.
3. Follows the [Rules of React](https://react.dev/reference/rules).

If you are unable to upgrade to React 19, you may try a userspace implementation of the cache function as described in the [Working Group](https://github.com/reactwg/react-compiler/discussions/6). However, please note that this is not recommended and you should upgrade to React 19 when possible.
React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler).

### How do I know my components have been optimized? {/*how-do-i-know-my-components-have-been-optimized*/}

Expand Down
6 changes: 6 additions & 0 deletions src/content/reference/react/useReducer.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,17 @@ function MyComponent() {
#### Limitations et points à noter {/*caveats*/}
<<<<<<< HEAD
* `useReducer` est un Hook, vous ne pouvez donc l'appeler **qu'au niveau racine de votre composant** ou de vos propres Hooks. Vous ne pouvez pas l'appeler dans des boucles ou des conditions. Si vous avez besoin de le faire, extrayez un nouveau composant et déplacez-y l'état.
* La fonction `dispatch` a une identité stable, elle ne figure donc généralement pas dans les dépendances des Effets, mais l'inclure n'entraînera pas un déclenchement d'Effet superflu. Si le *linter* vous permet de l'omettre sans erreurs, c'est que cette omission est sans danger. [Apprenez-en davantage sur l'allègement des dépendances d'Effets](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
* En Mode Strict, React **appellera deux fois votre réducteur et votre fonction d'initialisation** afin de [vous aider à détecter des impuretés accidentelles](#my-reducer-or-initializer-function-runs-twice). Ce comportement est limité au développement et n'affecte pas la production. Si votre réducteur et votre fonction d'initialisation sont pures (ce qui devrait être le cas), ça n'impactera pas votre logique. Le résultat de l'un des appels est ignoré.
=======
* `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* The `dispatch` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
* In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.](#my-reducer-or-initializer-function-runs-twice) This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect your logic. The result from one of the calls is ignored.
>>>>>>> 9467bc58868e66c53ca9385c8531dcf7b02178c2
---
Expand Down
4 changes: 4 additions & 0 deletions src/content/reference/react/useState.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ Les fonctions de mise à jour (celles renvoyées par `useState`) n'ont pas de va
* React [met à jour les états par lots](/learn/queueing-a-series-of-state-updates). Il met à jour l'écran **après que tous les gestionnaires d'événements ont été lancés** et qu'ils auront appelé leurs fonctions de mise à jour. Ça évite des rendus inutiles suite à un unique événement. Dans les rares cas où vous auriez besoin de forcer React à mettre à jour l'écran plus tôt, par exemple pour accéder au DOM, vous pouvez utiliser [`flushSync`](/reference/react-dom/flushSync).
<<<<<<< HEAD
* La fonction de mise à jour a une identité stable, elle ne figure donc généralement pas dans les dépendances des Effets, mais l'inclure n'entraînera pas un déclenchement d'Effet superflu. Si le *linter* vous permet de l'omettre sans erreurs, c'est que cette omission est sans danger. [Apprenez-en davantage sur l'allègement des dépendances d'Effets](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
=======
* The `set` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
>>>>>>> 9467bc58868e66c53ca9385c8531dcf7b02178c2
* Il est possible d'appeler la fonction de mise à jour *pendant le rendu*, mais uniquement au sein du composant en cours de rendu. React ignorera le JSX résultat pour refaire immédiatement un rendu avec le nouvel état. Cette approche est rarement nécessaire, mais vous pouvez l'utiliser pour **stocker des informations des précédents rendus**. [Voir un exemple ci-dessous](#storing-information-from-previous-renders).
Expand Down
Loading

0 comments on commit 16c6566

Please sign in to comment.