This React pattern optimizes performance in functional components by preventing unnecessary re-renders using the useMemo and useCallback hooks. It is ...
Back to Snippets
javascript
• 47 lines
JavaScript
JavaScript
JavaScript
Custom React Hook For Handling Async Operations
This snippet provides a reusable React hook for managing asynchronous operations, including error handling and loading states. Use this hook when you need to fetch data from an API or perform other async tasks in your React application. It helps to keep your code organized and makes it easier to handle loading and error states.
Snippet Stats
Lines
47
Characters
1,408
Read
2 mins
import { useState, useEffect } from 'react';
// Custom hook for handling async operations
const useAsync = (asyncFunction, immediate = true) => {
// State to store the result of the async operation
const [status, setStatus] = useState('idle');
// State to store the result of the async operation
const [value, setValue] = useState(null);
// State to store the error
const [error, setError] = useState(null);
// Function to execute the async operation
const execute = useCallback(() => {
// Set the status to 'pending' before executing the async operation
setStatus('pending');
// Reset the error and value
setError(null);
setValue(null);
return asyncFunction()
.then((response) => {
// Set the status to 'success' and store the result
setStatus('success');
setValue(response);
})
.catch((error) => {
// Set the status to 'error' and store the error
setStatus('error');
setError(error);
});
}, [asyncFunction]);
// Execute the async operation immediately if required
useEffect(() => {
if (immediate) {
execute();
}
}, [immediate, execute]);
return { execute, status, value, error };
};
// Example usage:
// const { execute, status, value, error } = useAsync(() => {
// return fetch('https://api.example.com/data')
// .then((response) => response.json());
// });
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis React code snippet utilizes the Context API along with the useMemo hook to optimize performance by sharing data between components efficiently. I...
This code snippet demonstrates how to optimize React hooks using useCallback and useMemo to prevent unnecessary re-renders and improve performance. It...