Use the React.lazy and Suspense components to implement code-splitting
Learn how to optimize performance in React with the useMemo hook and React.memo
- Published on
7 min read
•
10 Best Practices for Writing Efficient and Maintainable React Applications
Table of Contents
- Introduction
- Problem statement
- Solution
- Code splitting on Component level
- Step 1: Import React.lazy and Suspense
- Step 2: Defining the dynamic import
- Step 3: Use the DynamicComponent with Suspense
- Code splitting on Route level
- Step 1: Import React.lazy and Suspense
- Step 2: Define a dynamic import
- Step 3: Usage on Suspense to use the DynamicComponent
Introduction
By minimizing the amount of code that needs to be loaded at once, code splitting enables you to separate your code into smaller chunks and only load the pieces required for a certain route or component. This improves the performance of your React application.
To implement code splitting in a React application, you can use the React.lazy
function and the Suspense
component. The React.lazy
function enables you to dynamically import a component, and the Suspense
component allows you to specify a fallback component to display while the component is being loaded.
Problem statement
There are several problems that can arise when not using code splitting in a React application:
- Large Initial Payload : The initial payload size may be huge if your application is large and has lots of components and routes, which may cause the user to wait longer for pages to load. For people with slower internet connections, this might be very difficult.
- Slow performance : The performance of the application may suffer if the entire source code is loaded up front since the browser must parse and run the entire source code before the application can be presented.
- Higher memory usage : Because the browser must maintain all of the code in memory while the application is running, loading all of the code at once might also result in higher memory utilization.
Solution
Code splitting allows you to avoid these issues by just loading the code required for a particular route or component, which can enhance the application's initial load time and overall speed. Code splitting can be done on Component level and Routing level.
Code splitting on Component level
Step 1: Import React.lazy and Suspense
Import React.lazy and Suspense by adding the following line to the top of your file:
import React, { Suspense, lazy } from 'react'
Step 2: Defining the dynamic import
A dynamic import can be defined by using the lazy
function. The dynamic import returns a promise that gets resolved to the module that is being imported.
const DynamicComponent = lazy(() => import('./Component'))
Step 3: Use the DynamicComponent with Suspense
Now that we have defined our dynamic import, we need to wrap the component with the Suspense component. The Suspense component allows us to specify a fallback component to display while the component is being loaded.
<Suspense fallback={<div>Loading...</div>}>
<DynamicComponent />
</Suspense>
The Loading...
message will be displayed while the DynamicComponent
is being loaded.
Here is an example of how you might use the DynamicComponent in a parent component:
const ParentComponent = () => {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
)
}
React.lazy
and Suspense
make it simple to implement code splitting, which can be a great tool for enhancing the efficiency of your React application. You can decrease the initial payload size and enhance the performance of your application by only loading the code required for a particular route or component.
Code splitting on Route level
Instead of loading the entire application's code at once, code splitting at the route level enables you to just load the code for a particular route when it is required.
Step 1: Import React.lazy and Suspense
Import React.lazy and Suspense by adding the following line to the top of your file:
import React, { Suspense, lazy } from 'react'
Step 2: Define a dynamic import
Similar to the step 2 from Component level we need to defined the dynamic component.
const DynamicComponent = lazy(() => import('./Component'))
Step 3: Usage on Suspense to use the DynamicComponent
Now that we have defined our dynamic import and wrapped it with the Suspense component, we can define a route for the component using a routing library such as react-router. Here is an example of how you might define a route for the OtherComponent using react-router:
import React, { Suspense, lazy } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
const DynamicComponent = lazy(() => import('./Component'))
ReactDOM.render(
<Router>
<Route
path="/other"
render={() => (
<Suspense fallback={<div>Loading...</div>}>
<DynamicComponent />
</Suspense>
)}
/>
</Router>
)
Here is different example that uses the route base splitting: The other way to do it is to wrap the Switch
with the Suspense
const App = lazy(() => import('./App'))
const About = lazy(() => import('./About'))
const Contact = lazy(() => import('./Contact'))
ReactDOM.render(
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/">
<App />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
</Suspense>
</Router>,
document.getElementById('root')
)
Using React.lazy
and Suspense
you have now successfully implemented code splitting at the route level in your React application. When it comes to employing React
code splitting at the route level can be a very effective method for increasing the performance of your React application.
That's a wrap!
Happy coding!