0% completed
React.lazy and React Suspense provide an efficient solution for dynamically loading components. However, to fully appreciate their value, it’s important to first understand the problem they aim to solve.
Let’s look at an example that illustrates the issue that lazy loading was designed to address:
Consider a scenario where we import all components at once:
import Header from './Header'; import Sidebar from './Sidebar'; import Dashboard from './Dashboard'; function App() { return ( <div> <Header /> <Sidebar /> <Dashboard /> </div> ); } export default App;
In this case, all components (Header, Sidebar, and Dashboard) are loaded at the same time, even if the user doesn’t immediately need all of them. This leads to longer initial load times. But, with lazy loading techniques, this problem can be addressed.
React provides React.lazy() to load components dynamically. This built-in function enables component-level code splitting, meaning that the component will only be loaded when needed. In simpler terms, React.lazy() is a built-in function that allows React components to be dynamically imported, i.e., loaded only when they are required.
It takes a function that returns a dynamic import(), which is how the component gets loaded asynchronously.
const Component = React.lazy(() => import('./Component'));
Instead of importing a component at the top, we wrap it inside React.lazy(), which returns a Promise that resolves to the module.
Suspense is a React component that allows you to handle the loading state of lazily-loaded components. You wrap the lazily-loaded components inside Suspense and provide a fallback UI (like a loading spinner or message) to be shown while the component is being fetched.
<Suspense fallback={<div>Loading...</div>}> <MyComponent /> </Suspense>
Now, you have an idea of what they are and their syntax, lets look at how we can combine them both in an example to achieve our performance goals:
import React, { Suspense } from 'react'; const Dashboard = React.lazy(() => import('./Dashboard')); function App() { return ( <div> <h1>Welcome to My App</h1> <Suspense fallback={<p>Loading Dashboard...</p>}> <Dashboard /> </Suspense> </div> ); } export default App;
In this code example,
<p>
Loading Dashboard...</p>
) while it is being loaded.This means the component is loaded only when required, reducing the initial bundle size.
.....
.....
.....