Movatterモバイル変換


[0]ホーム

URL:


We want to hear from you!Take our 2021 Community Survey!
This site is no longer updated.Go to react.dev

Code-Splitting

These docs are old and won’t be updated. Go toreact.dev for the new React docs.

These new documentation pages teach modern React and include live examples:

Bundling

Most React apps will have their files “bundled” using tools likeWebpack,Rollup orBrowserify. 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

App:

// app.jsimport{ add}from'./math.js';console.log(add(16,26));// 42
// math.jsexportfunctionadd(a, b){return a+ b;}

Bundle:

functionadd(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 usingCreate React App,Next.js,Gatsby, 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 theInstallation andGetting Started guides on the Webpack docs.

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 featuresupported by bundlers likeWebpack,Rollup and Browserify (viafactor-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()

The best way to introduce code-splitting into your app is through the dynamicimport() syntax.

Before:

import{ add}from'./math';console.log(add(16,26));

After:

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 canstart using it immediately. It’s also supported out of the box inNext.js.

If you’re setting up Webpack yourself, you’ll probably want to read Webpack’sguide on code splitting. Your Webpack config should look vaguelylike this.

When usingBabel, 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.

React.lazy

TheReact.lazy function lets you render a dynamic import as a regular component.

Before:

import OtherComponentfrom'./OtherComponent';

After:

const OtherComponent= React.lazy(()=>import('./OtherComponent'));

This will automatically load the bundle containing theOtherComponent when this component is first rendered.

React.lazy takes a function that must call a dynamicimport(). This must return aPromise which resolves to a module with adefault export containing a React component.

The lazy component should then be rendered inside aSuspense component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.

import React,{ Suspense}from'react';const OtherComponent= React.lazy(()=>import('./OtherComponent'));functionMyComponent(){return(<div><Suspensefallback={<div>Loading...</div>}><OtherComponent/></Suspense></div>);}

Thefallback prop accepts any React elements that you want to render while waiting for the component to load. You can place theSuspense component anywhere above the lazy component. You can even wrap multiple lazy components with a singleSuspense component.

import React,{ Suspense}from'react';const OtherComponent= React.lazy(()=>import('./OtherComponent'));const AnotherComponent= React.lazy(()=>import('./AnotherComponent'));functionMyComponent(){return(<div><Suspensefallback={<div>Loading...</div>}><section><OtherComponent/><AnotherComponent/></section></Suspense></div>);}

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:

import React,{ Suspense}from'react';import Tabsfrom'./Tabs';import Glimmerfrom'./Glimmer';const Comments= React.lazy(()=>import('./Comments'));const Photos= React.lazy(()=>import('./Photos'));functionMyComponent(){const[tab, setTab]= React.useState('photos');functionhandleTabSelect(tab){setTab(tab);};return(<div><TabsonTabSelect={handleTabSelect}/><Suspensefallback={<Glimmer/>}>{tab==='photos'?<Photos/>:<Comments/>}</Suspense></div>);}

In this example, if tab gets changed from'photos' to'comments', butComments suspends, the user will see a glimmer. This makes sense because the user no longer wants to seePhotos, theComments component is not ready to render anything, and React needs to keep the user experience consistent, so it has no choice but to show theGlimmer 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 newstartTransition API to make React do this:

functionhandleTabSelect(tab){startTransition(()=>{setTab(tab);});}

Here, you tell React that setting tab to'comments' is not an urgent update, but is atransition 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. SeeTransitions for more info.

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 withError Boundaries. 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.

import React,{ Suspense}from'react';import MyErrorBoundaryfrom'./MyErrorBoundary';const OtherComponent= React.lazy(()=>import('./OtherComponent'));const AnotherComponent= React.lazy(()=>import('./AnotherComponent'));constMyComponent=()=>(<div><MyErrorBoundary><Suspensefallback={<div>Loading...</div>}><section><OtherComponent/><AnotherComponent/></section></Suspense></MyErrorBoundary></div>);

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 likeReact Router withReact.lazy.

import React,{ Suspense, lazy}from'react';import{ BrowserRouteras Router, Routes, Route}from'react-router-dom';const Home=lazy(()=>import('./routes/Home'));const About=lazy(()=>import('./routes/About'));constApp=()=>(<Router><Suspensefallback={<div>Loading...</div>}><Routes><Routepath="/"element={<Home/>}/><Routepath="/about"element={<About/>}/></Routes></Suspense></Router>);

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.

// ManyComponents.jsexportconst MyComponent=/* ... */;exportconst MyUnusedComponent=/* ... */;
// MyComponent.jsexport{ MyComponentasdefault}from"./ManyComponents.js";
// MyApp.jsimport React,{ lazy}from'react';const MyComponent=lazy(()=>import("./MyComponent.js"));
Is this page useful?Edit this page

[8]ページ先頭

©2009-2025 Movatter.jp