React Suspense is a powerful feature that simplifies the process of lazy loading components in your React applications. By leveraging this built-in functionality, developers can optimize their app’s performance and improve the user experience. In this article, we will explore how to use React Suspense for lazy loading components effectively.
Understanding React Suspense
React Suspense allows you to defer rendering a part of your component tree until some condition is met, such as waiting for a fetch request or a dependency to resolve. This is particularly useful for lazy loading components, which can reduce the initial load time of your app.
Setting Up Lazy Loading with React Suspense
To implement lazy loading with React Suspense, you will need to use the `React.lazy` function and the `Suspense` component. Here's how you can do it:
Step 1: Import Necessary Functions
Begin by importing the `lazy` and `Suspense` functions from the React library:
import React, { lazy, Suspense } from 'react';
Step 2: Create a Lazy Loaded Component
You can define a component that you wish to load lazily using the `React.lazy` function. Here’s how you can do it:
const LazyComponent = lazy(() => import('./LazyComponent'));
In this example, `LazyComponent` is loaded only when it is rendered for the first time, thereby reducing the initial bundle size.
Step 3: Wrap Your Lazy Loaded Component with Suspense
Next, use the `Suspense` component to wrap your lazy loaded component. The `Suspense` component requires a `fallback` prop, which specifies what to display while the lazy component is loading:
function App() {
return (
Loading...
}>
);
}
Displaying a Loading Indicator
The `fallback` prop in the `Suspense` component can be customized to show any loading indicator. It could be a spinner, a skeleton screen, or a simple text message. This is essential for providing feedback to users while the content is being loaded.
Using Multiple Lazy Loaded Components
React Suspense can also manage multiple lazy loaded components. You simply wrap them in a single `Suspense` component. However, if you want different loading states for each component, you can create separate `Suspense` components for each one:
function App() {
return (
Loading Component 1...
}>
Loading Component 2...
}>