React suspense for data fetching
Created By: chatGPT
React Suspense is a feature that helps manage loading states in your application. It allows components to 'wait' for some asynchronous operation to complete before rendering. This can be particularly useful when fetching data in a component. Instead of having multiple loading states scattered throughout your app, you can consolidate them using Suspense.
import React, { Suspense } from 'react';
const MyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}
React.lazy is used to dynamically import a component. The
Suspense
component wraps your lazy-loaded component and provides a fallback UI while the component is loading. You can customize the fallback UI as needed.const MyComponent = React.lazy(() => import('./MyComponent'));
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
To fetch data with Suspense, you typically need to use a library that supports this functionality, like React Query or Relay. These libraries help you to handle the caching and fetching process while integrating seamlessly with Suspense.
import { useQuery } from 'react-query';
function DataComponent() {
const { data } = useQuery('fetchData', fetchDataFunction);
return <div>{data}</div>;
}
<Suspense fallback={<div>Loading...</div>}>
<DataComponent />
</Suspense>
In the above example,
useQuery
is a hook from React Query that fetches your data and provides it directly to the component. Using Suspense simplifies the loading state management, allowing you to focus on what to display while waiting for the data.function fetchDataFunction() {
return fetch('/api/data').then(res => res.json());
}
function DataComponent() {
const { data } = useQuery('fetchData', fetchDataFunction);
return <div>{data}</div>;
}
<Suspense fallback={<div>Loading...</div>}>
<DataComponent />
</Suspense>