Open In App

How to handle async operations with Custom Hooks ?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Handling asynchronous operations with custom Hooks involves using techniques like useState, useEffect, and asynchronous functions (async/await) to manage asynchronous logic within the Hook.

Handling Async operations with Custom Hooks:

  • State Management: Use useState to manage the state related to the asynchronous operation. This typically includes state variables for data, loading status, and error messages.
  • Effect Hook: Used useEffect to trigger the asynchronous operation and manage its lifecycle. Inside the useEffect callback, you can invoke asynchronous functions to fetch data, perform network requests, or any other async task.
  • Loading State: Set a loading state to indicate when the asynchronous operation is in progress. This allows components using the custom Hook to display loading indicators or disable UI elements while waiting for the operation to complete.
  • Cleanup: If necessary, perform cleanup tasks when the component unmounts or when dependencies change. This may involve canceling pending requests, unsubscribing from event listeners, or releasing resources acquired during the async operation.
  • Return Values: Return relevant data, loading status, and error state from the custom Hook so that components using the Hook can access and interact with it.

Example: Below is an example of handling async operations with custom Hooks.

Javascript




import React, {
    useState,
    useEffect
} from 'react';
 
function useAsyncOperation(url) {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
 
    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                setData(result);
            } catch (error) {
                setError(error);
            } finally {
                setIsLoading(false);
            }
        };
 
        fetchData();
        return () => {
        };
    }, [url]);
 
    return { data, isLoading, error };
}
function AsyncComponent() {
    const { data, isLoading, error } =
        useAsyncOperation('https://fakestoreapi.com/products');
 
    useEffect(() => {
        if (data) {
            console.log('Data fetched:', data);
        }
    }, [data]);
 
    useEffect(() => {
        if (error) {
            console.error('Error fetching data:', error);
        }
    }, [error]);
 
    return (
        <div>
            {isLoading && <p>Loading...</p>}
            {data && (
                <ul>
                    {data.map(item => (
                        <li key={item.id}>{item.title}
                            <b>Price</b> {item.price}
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}
 
export default AsyncComponent;


Output:

gfg61

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads