You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

260 lines
9.9 KiB

---
id: code-splitting
title: Code-Splitting
permalink: docs/code-splitting.html
---
## Bundling {#bundling}
Most React apps will have their files "bundled" using tools like [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/) or [Browserify](http://browserify.org/). Bundling is the process of following imported files and merging them into a single file: a "bundle". This bundle can then be included on a webpage to load an entire app at once.
#### Example {#example}
**App:**
```js
// app.js
import { add } from './math.js';
console.log(add(16, 26)); // 42
```
```js
// math.js
export function add(a, b) {
return a + b;
}
```
**Bundle:**
```js
function add(a, b) {
return a + b;
}
console.log(add(16, 26)); // 42
```
> Note:
>
> Your bundles will end up looking a lot different than this.
If you're using [Create React App](https://create-react-app.dev/), [Next.js](https://nextjs.org/), [Gatsby](https://www.gatsbyjs.org/), or a similar tool, you will have a Webpack setup out of the box to bundle your app.
If you aren't, you'll need to set up bundling yourself. For example, see the [Installation](https://webpack.js.org/guides/installation/) and [Getting Started](https://webpack.js.org/guides/getting-started/) guides on the Webpack docs.
## Code Splitting {#code-splitting}
Bundling is great, but as your app grows, your bundle will grow too. Especially if you are including large third-party libraries. You need to keep an eye on the code you are including in your bundle so that you don't accidentally make it so large that your app takes a long time to load.
To avoid winding up with a large bundle, it's good to get ahead of the problem and start "splitting" your bundle. Code-Splitting is a feature
supported by bundlers like [Webpack](https://webpack.js.org/guides/code-splitting/), [Rollup](https://rollupjs.org/guide/en/#code-splitting) and Browserify (via [factor-bundle](https://github.com/browserify/factor-bundle)) which can create multiple bundles that can be dynamically loaded at runtime.
Code-splitting your app can help you "lazy-load" just the things that are currently needed by the user, which can dramatically improve the performance of your app. While you haven't reduced the overall amount of code in your app, you've avoided loading code that the user may never need, and reduced the amount of code needed during the initial load.
## `import()` {#import}
The best way to introduce code-splitting into your app is through the dynamic `import()` syntax.
**Before:**
```js
import { add } from './math';
console.log(add(16, 26));
```
**After:**
```js
import("./math").then(math => {
console.log(math.add(16, 26));
});
```
When Webpack comes across this syntax, it automatically starts code-splitting your app. If you're using Create React App, this is already configured for you and you can [start using it](https://create-react-app.dev/docs/code-splitting/) immediately. It's also supported out of the box in [Next.js](https://nextjs.org/docs/advanced-features/dynamic-import).
If you're setting up Webpack yourself, you'll probably want to read Webpack's [guide on code splitting](https://webpack.js.org/guides/code-splitting/). Your Webpack config should look vaguely [like this](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).
When using [Babel](https://babeljs.io/), you'll need to make sure that Babel can parse the dynamic import syntax but is not transforming it. For that you will need [@babel/plugin-syntax-dynamic-import](https://classic.yarnpkg.com/en/package/@babel/plugin-syntax-dynamic-import).
## `React.lazy` {#reactlazy}
The `React.lazy` function lets you render a dynamic import as a regular component.
**Before:**
```js
import OtherComponent from './OtherComponent';
```
**After:**
```js
const OtherComponent = React.lazy(() => import('./OtherComponent'));
```
This will automatically load the bundle containing the `OtherComponent` when this component is first rendered.
`React.lazy` takes a function that must call a dynamic `import()`. This must return a `Promise` which resolves to a module with a `default` export containing a React component.
The lazy component should then be rendered inside a `Suspense` component, which allows us to show some fallback content (such as a loading indicator) while we're waiting for the lazy component to load.
```js
import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
```
The `fallback` prop accepts any React elements that you want to render while waiting for the component to load. You can place the `Suspense` component anywhere above the lazy component. You can even wrap multiple lazy components with a single `Suspense` component.
```js
import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</div>
);
}
```
React 18 (#4499) * [18] ReactDOM reference to createRoot/hydrateRoot (#4340) * [18] ReactDOM reference to createRoot/hydrateRoot * Update note about render and hydrate * Match the warning text * s/Render/render * [18] Update ReactDOMClient docs (#4468) * [18] Update ReactDOMClient docs * Remove ReactDOMClient where it&#39;s obvious * Update browser message * Update browser message note * Update based on feedback * Add react-dom/client docs * [18] Upgrade homepage examples (#4469) * [18] Switch code samples to createRoot (#4470) * [18] Switch code samples to createRoot * Feedback fixes * Feedback updates * [18] Use hydrateRoot and root.unmount. (#4473) * [18] Add docs for flushSync (#4474) * [18] Add flushSync to ReactDOM docs * Seb feedback * More Seb feedback * [18] Bump version to 18 (#4478) * [18] Update browser requirements (#4476) * [18] Update browser requirements * Update based on feedback * [18] Add stubs for new API references (#4477) * [18] Add stubs for new API references * Change order/grouping * [18] Redirect outdated Concurrent Mode docs (#4481) * [18] Redirect outdated Concurrent Mode docs * Use Vercel redirects instead * [18] Update versions page (#4482) * [18] Update version page * Fix prettier * [18] Update React.lazy docs (#4483) * [18] Add docs for useSyncExternalStore (#4487) * [18] Add docs for useSyncExternalStore * rm &#34;optional&#34; * [18] Add docs for useInsertionEffect (#4486) * [18] Add docs for useId (#4488) * [18] Add docs for useId * Update based on feedback * Add Strict Effects to Strict Mode (#4362) * Add Strict Effects to Strict Mode * Update with new thinking * [18] Update docs for useEffect timing (#4498) * [18] Add docs for useDeferredValue (#4497) * [18] Update suspense docs for unexpected fallbacks (#4500) * [18] Update suspense docs for unexpected fallbacks * Add inline code block * Feedback fixes * [18] Updated Suspense doc with behavior during SSR and Hydration (#4484) * update wording * wording * update events * Update content/docs/reference-react.md Co-authored-by: Sebastian Silbermann &lt;silbermann.sebastian@gmail.com&gt; * add link to selective hydration * remove some of the implementation details Co-authored-by: Sebastian Silbermann &lt;silbermann.sebastian@gmail.com&gt; * [18] renderToPipeableStream doc (#4485) * new streaming ssr api * add readable stream * code snippets * Rename strict effects / unsafe effects to use the reusable state terminology (#4505) * Add draft of 18 release post * Add links to speaker Twitter profiles * [18] Update upgrade guide * Fix typo in blog title * [18] Blog - add note for react native * [18] Add changelog info to blog posts * Edit Suspense for data fetching section * Update date * [18] Add links * Consistent title case * Update link to merged RFC * [18] Update APIs and links * [18] Add start/useTransition docs (#4479) * [18] Add start/useTransition docs * Updates based on feedback * [18] Generate heading IDs * Add note about Strict Mode * Just frameworks * Reorder, fix content * Typos * Clarify Suspense frameworks section * Revert lost changes that happened when I undo-ed in my editor Co-authored-by: salazarm &lt;salazarm@users.noreply.github.com&gt; Co-authored-by: Sebastian Silbermann &lt;silbermann.sebastian@gmail.com&gt; Co-authored-by: Sebastian Markbåge &lt;sebastian@calyptus.eu&gt; Co-authored-by: Andrew Clark &lt;git@andrewclark.io&gt; Co-authored-by: dan &lt;dan.abramov@gmail.com&gt;
3 years ago
### Avoiding fallbacks {#avoiding-fallbacks}
Any component may suspend as a result of rendering, even components that were already shown to the user. In order for screen content to always be consistent, if an already shown component suspends, React has to hide its tree up to the closest `<Suspense>` boundary. However, from the user's perspective, this can be disorienting.
Consider this tab switcher:
```js
import React, { Suspense } from 'react';
import Tabs from './Tabs';
import Glimmer from './Glimmer';
const Comments = React.lazy(() => import('./Comments'));
const Photos = React.lazy(() => import('./Photos'));
function MyComponent() {
const [tab, setTab] = React.useState('photos');
function handleTabSelect(tab) {
setTab(tab);
};
return (
<div>
<Tabs onTabSelect={handleTabSelect} />
<Suspense fallback={<Glimmer />}>
{tab === 'photos' ? <Photos /> : <Comments />}
</Suspense>
</div>
);
}
```
In this example, if tab gets changed from `'photos'` to `'comments'`, but `Comments` suspends, the user will see a glimmer. This makes sense because the user no longer wants to see `Photos`, the `Comments` component is not ready to render anything, and React needs to keep the user experience consistent, so it has no choice but to show the `Glimmer` above.
However, sometimes this user experience is not desirable. In particular, it is sometimes better to show the "old" UI while the new UI is being prepared. You can use the new [`startTransition`](/docs/react-api.html#starttransition) API to make React do this:
```js
function handleTabSelect(tab) {
startTransition(() => {
setTab(tab);
});
}
```
Here, you tell React that setting tab to `'comments'` is not an urgent update, but is a [transition](/docs/react-api.html#transitions) that may take some time. React will then keep the old UI in place and interactive, and will switch to showing `<Comments />` when it is ready. See [Transitions](/docs/react-api.html#transitions) for more info.
### Error boundaries {#error-boundaries}
If the other module fails to load (for example, due to network failure), it will trigger an error. You can handle these errors to show a nice user experience and manage recovery with [Error Boundaries](/docs/error-boundaries.html). Once you've created your Error Boundary, you can use it anywhere above your lazy components to display an error state when there's a network error.
```js
import React, { Suspense } from 'react';
import MyErrorBoundary from './MyErrorBoundary';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
const MyComponent = () => (
<div>
<MyErrorBoundary>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</MyErrorBoundary>
</div>
);
```
## Route-based code splitting {#route-based-code-splitting}
Deciding where in your app to introduce code splitting can be a bit tricky. You want to make sure you choose places that will split bundles evenly, but won't disrupt the user experience.
A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.
Here's an example of how to setup route-based code splitting into your app using libraries like [React Router](https://reactrouter.com/) with `React.lazy`.
```js
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</Router>
);
```
## Named Exports {#named-exports}
`React.lazy` currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don't pull in unused components.
```js
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
```
```js
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
```
```js
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));
```