
Table of Contents
Orerview:
React Suspense is a component that allows developers to handle the loading state of certain components in a declarative manner. It allows developers to define a fallback component that will be displayed while the component is loading.
To use React Suspense in a functional component, you can import the Suspense
component from the ‘react’ library and wrap the component that you want to load in it. You can also provide a fallback component as a prop to the Suspense
component that will be displayed while the wrapped component is loading.
You can read – Top 12 Advantages of Using React Suspense & Lazy Functions
Example of using Suspense Component:
For example, let’s say we have a component called MyComponent
that takes some time to load. We can use React Suspense to handle the loading state of this component as follows:
import { Suspense } from 'react';
function MyComponent() {
// component code
}
function MyApp() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}
In this example, while MyComponent
is loading, the text “Loading…” will be displayed. Once MyComponent
has finished loading, it will be displayed in place of the fallback.
Another way to use React Suspense is by using the lazy
function, which allows you to load a component lazily. It returns a special component that can be rendered inside a Suspense
component.
import { Suspense, lazy } from 'react';
const MyComponent = lazy(() => import('./MyComponent'));
function MyApp() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}
In this example, MyComponent
will be loaded only when it is rendered for the first time. This way, you can save the initial load time of your application.
Summary:
React Suspense is a powerful tool that allows developers to handle the loading state of their components in a declarative manner. It can be used in both class-based and functional components, and it can be used to load components lazily. With examples like above, you can now easily implement React Suspense in your React application.