In React, when we build a large application, it may contain many components and pages. Loading all the JavaScript code at once can increase the initial loading time of the application.
To solve this problem, React provides two important features:
- React.lazy() – Loads a component's code only when it is needed.
- Suspense – Displays a fallback UI while the component is loading.
Together, these features help us implement code splitting and improve the loading experience of a React application.
What is React.lazy()?
React.lazy() is a React function that allows us to load a component dynamically instead of loading it immediately.
This technique is called lazy loading.
In simple words, React.lazy() loads a component's code only when React needs to render that component.
Syntax:
import { lazy } from "react";
const MyComponent = lazy(() => {
return import("./MyComponent");
});
What is Suspense in React?
Suspense is a React component that allows us to display a fallback UI while its child component is not ready to render.
In simple words, Suspense shows a temporary loading screen until the required component is ready.
Syntax:
import { Suspense } from "react";
<Suspense fallback={<h2>Loading...</h2>}>
<MyComponent />
</Suspense>
Top comments (0)