In React, suspense is a feature that allows components to "suspend" rendering while they wait for some asynchronous operation to complete, such as fetching data from an API or loading a code-split module. It helps improve the user experience by allowing your application to gracefully handle delays in data fetching or code loading.
Here's how suspense works in React:
-
Data Fetching:
Suspense is commonly used with the
React.lazy
function and theimport()
syntax for dynamic imports. For example, when you have a component that needs to asynchronously fetch data, you can useReact.lazy
along with a function that returns a promise (usually, the dynamic import).
const MyComponent = React.lazy(() => import('./MyComponent'));
- Error Boundary: To handle errors during the asynchronous operations, you can use an error boundary. Error boundaries are special React components that can catch JavaScript errors anywhere in their child component tree.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
-
Suspense Component:
Use the
Suspense
component to wrap the part of your tree that may suspend. You can provide afallback
prop to specify what to render while waiting for the suspended component to load.
import React, { Suspense } from 'react';
const MyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
</div>
);
}
With this setup, if MyComponent
takes time to load, the Suspense
component will show the fallback UI until the component is ready to be rendered. If there's an error during the loading process, the error boundary will catch it and display an error message.
In summary, suspense in React is a mechanism for handling asynchronous operations in a more declarative and user-friendly way, providing a smoother experience for users while your application loads and processes data.