React suspense
Created By: chatGPT
React Suspense is a powerful feature that allows you to create a smoother user experience by waiting for some asynchronous data to be loaded before rendering components. This is particularly useful when fetching data or loading code-split bundles. With Suspense, you can specify a fallback UI that will be displayed while the data is being fetched.
import React, { Suspense } from 'react';
const MyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}
export default App;
In this example,
MyComponent
is lazily loaded. When MyComponent
is being fetched, the fallback designated by Suspense
, which in this case is <div>Loading...</div>
, will be shown until the component is ready to be rendered.import React, { useState, useEffect } from 'react';
const DataFetchingComponent = ({ resource }) => {
const [data, setData] = useState(null);
useEffect(() => {
// Simulate a data fetching process
const fetchData = async () => {
const response = await fetch(resource);
const jsonData = await response.json();
setData(jsonData);
};
fetchData();
}, [resource]);
if (!data) {
throw new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate loading
}
return <div>{JSON.stringify(data)}</div>;
};
export default DataFetchingComponent;
In the
DataFetchingComponent
, while the data is being fetched, it throws a promise which tells React to suspend rendering until the data has been loaded. This also helps in integrating with React Concurrent Mode.const App = () => {
return (
<Suspense fallback={<div>Loading data...</div>}>
<DataFetchingComponent resource="https://api.example.com/data" />
</Suspense>
);
};
export default App;
This setup allows the
App
component to display a loading state while waiting for the DataFetchingComponent
to retrieve the necessary data. The eloquent use of Suspense here provides a seamless experience, reducing the perceived loading time.import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));