Open In App

How to handle Suspense with Hooks in React ?

Suspense is a feature that allows components to suspend rendering while waiting for some asynchronous operation to resolve, such as data fetching. With React Hooks, you can use Suspense along with the useEffect hook for handling asynchronous operations.

Handling Suspense with Hooks:

Example: Below is an example of handling suspense with Hooks.




import React, {
    useState,
    useEffect,
    Suspense
} from 'react';
 
const fetchData = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve([
                {
                    id: 1,
                    name: 'GeeksforGeeks'
                },
                {
                    id: 2,
                    name: 'GeeksforGeeks Web Tech'
                },
                {
                    id: 3,
                    name: 'GFG Mern Stack'
                }
            ]);
        }, 2000);
    });
};
 
const DataFetchingComponent = () => {
    const [data, setData] = useState(null);
 
    useEffect(() => {
        fetchData()
            .then(data => setData(data));
    }, []);
 
    const example =
        data ? data[0] : null;
 
    return (
        <div>
            <h2>Data Fetching Component</h2>
            <Suspense fallback={<div>Loading...</div>}>
                {
                    example ? (
                        <div>
                            <h3>Example:</h3>
                            <p>ID: {example.id}</p>
                            <p>Name: {example.name}</p>
                        </div>
                    ) : null
                }
            </Suspense>
        </div>
    );
};
 
export default DataFetchingComponent;

Output:

Output


Article Tags :