What is React.lazy?
- React course
- Intermediate
- Lesson 57/80
- 4 min
Learn to lazily load components with React.lazy.
What is React.lazy?
React.lazy loads a component on demand instead of at the initial render. This enables code splitting; the app's initial bundle shrinks.
Usage is simple: const Heavy = React.lazy(() => import('./Heavy')). When the component is called, the module is fetched from the browser. During this time a loading indicator is needed.
This is where Suspense comes in; it shows a fallback until loading completes.
Suspense boundary
The Suspense component shows a fallback while its children load. The fallback prop takes the content to render during loading.
Example: <Suspense fallback={"{"<Spinner />}"}><Heavy /></Suspense>. Until Heavy loads, Spinner renders; once loaded, Heavy renders.
You wrap Suspense around the lazy component. With multiple lazy components a single Suspense can wrap them all.
Practice lazy and Suspense
Complete the skeleton below. Define Heavy with React.lazy; write an App component that returns <Suspense fallback={"{"<Spinner />}"}><Heavy /></Suspense>. Export it.
Starter code
import { lazy, Suspense } from "react";
// Define Heavy with lazy and write the App component hereSample solution
import { lazy, Suspense } from "react";
const Heavy = lazy(() => import("./Heavy"));
function App() {
return (
<Suspense fallback={<Spinner />}>
<Heavy />
</Suspense>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does React.lazy provide?
- Code splitting Correct answer
- Faster rendering
- Daha az state
- Daha az prop
Explanation: React.lazy provides code splitting; the initial bundle shrinks.
2 lazy call
const Heavy = React.lazy(() => ____);
const Heavy = React.lazy(() => import('./Heavy'));
Explanation: import('./Heavy') returns the dynamic import.
3 What is React.lazy: match the terms
| Term | Meaning |
|---|---|
React.lazy |
Dynamic import |
Suspense |
Loading boundary |
fallback |
Fallback content |
import() |
Loads a module |