Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
263 changes: 263 additions & 0 deletions src/content/learn/react-compiler/installation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
---
title: Installation
---

<Intro>
This guide will help you install and configure React Compiler in your React application.
</Intro>

<YouWillLearn>

* How to install React Compiler
* Basic configuration for different build tools
* How to verify your setup is working

</YouWillLearn>

## Prerequisites {/*prerequisites*/}

React Compiler is designed to work best with React 19, but it also supports React 17 and 18. Learn more about [React version compatibility](/reference/react-compiler/target).

## Installation {/*installation*/}

Install React Compiler as a `devDependency`:

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

Or with Yarn:

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

Or with pnpm:

<TerminalBlock>
pnpm install -D babel-plugin-react-compiler@latest
</TerminalBlock>

## Basic Setup {/*basic-setup*/}

React Compiler is designed to work by default without any configuration. However, if you need to configure it in special circumstances (for example, to target React versions below 19), refer to the [compiler options reference](/reference/react-compiler/configuration).

The setup process depends on your build tool. React Compiler includes a Babel plugin that integrates with your build pipeline.

<Pitfall>
React Compiler must run **first** in your Babel plugin pipeline. The compiler needs the original source information for proper analysis, so it must process your code before other transformations.
</Pitfall>

### Babel {/*babel*/}

Create or update your `babel.config.js`:

```js {3}
module.exports = {
plugins: [
'babel-plugin-react-compiler', // must run first!
// ... other plugins
],
// ... other config
};
```

### Vite {/*vite*/}

If you use Vite with version 6.0.0 or later of `@vitejs/plugin-react`, you can use the `reactCompilerPreset`:

<TerminalBlock>
npm install -D @rolldown/plugin-babel
</TerminalBlock>

```js {3-4,9-11}
// vite.config.js
import { defineConfig } from 'vite';
import react, { reactCompilerPreset } from '@vitejs/plugin-react';
import babel from '@rolldown/plugin-babel';

export default defineConfig({
plugins: [
react(),
babel({
presets: [reactCompilerPreset()]
}),
],
});
```

<Note>
In `@vitejs/plugin-react@6.0.0`, the inline Babel option was removed. If you're using an older version, you can use:

```js
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
plugins: [
react({
babel: {
plugins: ['babel-plugin-react-compiler'],
},
}),
],
});
```
</Note>

Alternatively, you can use the Babel plugin directly with `@rolldown/plugin-babel`:

```js {3,9}
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import babel from '@rolldown/plugin-babel';

export default defineConfig({
plugins: [
react(),
babel({
plugins: ['babel-plugin-react-compiler'],
}),
],
});
```

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

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

### React Router {/*usage-with-react-router*/}
Install `vite-plugin-babel`, and add the compiler's Babel plugin to it:

<TerminalBlock>
npm install vite-plugin-babel
</TerminalBlock>

```js {3-4,16}
// vite.config.js
import { defineConfig } from "vite";
import babel from "vite-plugin-babel";
import { reactRouter } from "@react-router/dev/vite";

const ReactCompilerConfig = { /* ... */ };

export default defineConfig({
plugins: [
reactRouter(),
babel({
filter: /\.[jt]sx?$/,
babelConfig: {
presets: ["@babel/preset-typescript"], // if you use TypeScript
plugins: [
["babel-plugin-react-compiler", ReactCompilerConfig],
],
},
}),
],
});
```

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

A community webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).

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

Please refer to [Expo's docs](https://docs.expo.dev/guides/react-compiler/) to enable and use the React Compiler in Expo apps.

### Metro (React Native) {/*usage-with-react-native-metro*/}

React Native uses Babel via Metro, so refer to the [Usage with Babel](#babel) section for installation instructions.

### Rspack {/*usage-with-rspack*/}

Please refer to [Rspack's docs](https://rspack.dev/guide/tech/react#react-compiler) to enable and use the React Compiler in Rspack apps.

### Rsbuild {/*usage-with-rsbuild*/}

Please refer to [Rsbuild's docs](https://rsbuild.dev/guide/framework/react#react-compiler) to enable and use the React Compiler in Rsbuild apps.


## ESLint Integration {/*eslint-integration*/}

React Compiler includes an ESLint rule that helps identify code that can't be optimized. When the ESLint rule reports an error, it means the compiler will skip optimizing that specific component or hook. This is safe: the compiler will continue optimizing other parts of your codebase. You don't need to fix all violations immediately. Address them at your own pace to gradually increase the number of optimized components.

Install the ESLint plugin:

<TerminalBlock>
npm install -D eslint-plugin-react-hooks@latest
</TerminalBlock>

If you haven't already configured eslint-plugin-react-hooks, follow the [installation instructions in the readme](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#installation). The compiler rules are available in the `recommended-latest` preset.

The ESLint rule will:
- Identify violations of the [Rules of React](/reference/rules)
- Show which components can't be optimized
- Provide helpful error messages for fixing issues

## Verify Your Setup {/*verify-your-setup*/}

After installation, verify that React Compiler is working correctly.

### Check React DevTools {/*check-react-devtools*/}

Components optimized by React Compiler will show a "Memo ✨" badge in React DevTools:

1. Install the [React Developer Tools](/learn/react-developer-tools) browser extension
2. Open your app in development mode
3. Open React DevTools
4. Look for the ✨ emoji next to component names

If the compiler is working:
- Components will show a "Memo ✨" badge in React DevTools
- Expensive calculations will be automatically memoized
- No manual `useMemo` is required

### Check Build Output {/*check-build-output*/}

You can also verify the compiler is running by checking your build output. The compiled code will include automatic memoization logic that the compiler adds automatically.

```js
import { c as _c } from "react/compiler-runtime";
export default function MyApp() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <div>Hello World</div>;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}

```

## Troubleshooting {/*troubleshooting*/}

### Opting out specific components {/*opting-out-specific-components*/}

If a component is causing issues after compilation, you can temporarily opt it out using the `"use no memo"` directive:

```js
function ProblematicComponent() {
"use no memo";
// Component code here
}
```

This tells the compiler to skip optimization for this specific component. You should fix the underlying issue and remove the directive once resolved.

For more troubleshooting help, see the [debugging guide](/learn/react-compiler/debugging).

## Next Steps {/*next-steps*/}

Now that you have React Compiler installed, learn more about:

- [React version compatibility](/reference/react-compiler/target) for React 17 and 18
- [Configuration options](/reference/react-compiler/configuration) to customize the compiler
- [Incremental adoption strategies](/learn/react-compiler/incremental-adoption) for existing codebases
- [Debugging techniques](/learn/react-compiler/debugging) for troubleshooting issues
- [Compiling Libraries guide](/reference/react-compiler/compiling-libraries) for compiling your React library
100 changes: 100 additions & 0 deletions src/content/reference/react/useOptimistic.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,108 @@ function AppContainer() {

#### Returns {/*returns*/}

<<<<<<< HEAD
* `optimisticState`: The resulting optimistic state. It is equal to `state` unless an action is pending, in which case it is equal to the value returned by `updateFn`.
* `addOptimistic`: `addOptimistic` is the dispatching function to call when you have an optimistic update. It takes one argument, `optimisticValue`, of any type and will call the `updateFn` with `state` and `optimisticValue`.
=======
`useOptimistic` returns an array with exactly two values:

1. `optimisticState`: The current optimistic state. It is equal to `value` unless an Action is pending, in which case it is equal to the state returned by `reducer` (or the value passed to the set function if no `reducer` was provided).
2. The [`set` function](#setoptimistic) that lets you update the optimistic state to a different value inside an Action.

---

### `set` functions, like `setOptimistic(optimisticState)` {/*setoptimistic*/}

The `set` function returned by `useOptimistic` lets you update the state for the duration of an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). You can pass the next state directly, or a function that calculates it from the previous state:

```js
const [optimisticLike, setOptimisticLike] = useOptimistic(false);
const [optimisticSubs, setOptimisticSubs] = useOptimistic(subs);

function handleClick() {
startTransition(async () => {
setOptimisticLike(true);
setOptimisticSubs(a => a + 1);
await saveChanges();
});
}
```

#### Parameters {/*setoptimistic-parameters*/}

* `optimisticState`: The value that you want the optimistic state to be during an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). If you provided a `reducer` to `useOptimistic`, this value will be passed as the second argument to your reducer. It can be a value of any type.
* If you pass a function as `optimisticState`, it will be treated as an _updater function_. It must be pure, should take the pending state as its only argument, and should return the next optimistic state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying the queued updaters to the previous state similar to [`useState` updaters](/reference/react/useState#setstate-parameters).

#### Returns {/*setoptimistic-returns*/}

`set` functions do not have a return value.

#### Caveats {/*setoptimistic-caveats*/}

* The `set` function must be called inside an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). If you call the setter outside an Action, [React will show a warning](#an-optimistic-state-update-occurred-outside-a-transition-or-action) and the optimistic state will briefly render.

<DeepDive>

#### How optimistic state works {/*how-optimistic-state-works*/}

`useOptimistic` lets you show a temporary value while an Action is in progress:

```js
const [value, setValue] = useState('a');
const [optimistic, setOptimistic] = useOptimistic(value);

startTransition(async () => {
setOptimistic('b');
const newValue = await saveChanges('b');
setValue(newValue);
});
```

When the setter is called inside an Action, `useOptimistic` will trigger a re-render to show that state while the Action is in progress. Otherwise, the `value` passed to `useOptimistic` is returned.

This state is called the "optimistic" because it is used to immediately present the user with the result of performing an Action, even though the Action actually takes time to complete.

**How the update flows**

1. **Update immediately**: When `setOptimistic('b')` is called, React immediately renders with `'b'`.

2. **(Optional) await in Action**: If you await in the Action, React continues showing `'b'`.

3. **Transition scheduled**: `setValue(newValue)` schedules an update to the real state.

4. **(Optional) wait for Suspense**: If `newValue` suspends, React continues showing `'b'`.

5. **Single render commit**: Finally, the `newValue` commits for `value` and `optimistic`.

There's no extra render to "clear" the optimistic state. The optimistic and real state converge in the same render when the Transition completes.

<Note>

#### Optimistic state is temporary {/*optimistic-state-is-temporary*/}

Optimistic state only renders while an Action is in progress, otherwise `value` is rendered.

If `saveChanges` returned `'c'`, then both `value` and `optimistic` will be `'c'`, not `'b'`.

</Note>

**How the final state is determined**

The `value` argument to `useOptimistic` determines what displays after the Action finishes. How this works depends on the pattern you use:

- **Hardcoded values** like `useOptimistic(false)`: After the Action, `state` is still `false`, so the UI shows `false`. This is useful for pending states where you always start from `false`.

- **Props or state passed in** like `useOptimistic(isLiked)`: If the parent updates `isLiked` during the Action, the new value is used after the Action completes. This is how the UI reflects the result of the Action.

- **Reducer pattern** like `useOptimistic(items, fn)`: If `items` changes while the Action is pending, React re-runs your `reducer` with the new `items` to recalculate the state. This keeps your optimistic additions on top of the latest data.

**What happens when the Action fails**

If the Action throws an error, the Transition still ends, and React renders with whatever `value` currently is. Since the parent typically only updates `value` on success, a failure means `value` hasn't changed, so the UI shows what it showed before the optimistic update. You can catch the error to show a message to the user.

</DeepDive>
>>>>>>> 47e64bf7ad81aab8bacfa791a37816ee869135eb

---

Expand Down
Loading