JAVASCRIPT
Custom React Hook for Asynchronous Data Fetching
Manage the lifecycle of any asynchronous operation (loading, error, data) with a clean, reusable React hook. Simplifies data fetching and state management for API calls.
import { useState, useEffect, useCallback } from 'react';
function useAsync(asyncFunction, immediate = true) {
const [status, setStatus] = useState('idle');
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
// The execute function calls the async function and sets the state accordingly
const execute = useCallback(() => {
setStatus('pending');
setValue(null);
setError(null);
return asyncFunction()
.then((response) => {
setValue(response);
setStatus('success');
})
.catch((err) => {
setError(err);
setStatus('error');
});
}, [asyncFunction]);
// Call execute if we want to fire it right away
// otherwise it's just a callable function
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, status, value, error };
// Example Usage:
// function UserProfile({ userId }) {
// const fetchUser = useCallback(() => {
// return fetch(`/api/users/${userId}`).then(res => res.json());
// }, [userId]);
//
// const { execute, status, value: user, error } = useAsync(fetchUser, true);
//
// if (status === 'pending') return <div>Loading user...</div>;
// if (status === 'error') return <div>Error: {error.message}</div>;
// if (status === 'success' && user) {
// return (
// <div>
// <h3>{user.name}</h3>
// <p>{user.email}</p>
// <button onClick={execute}>Refresh</button>
// </div>
// );
// }
// return null;
// }
How it works: The `useAsync` hook provides a robust way to manage the state of an asynchronous operation, such as fetching data from an API. It tracks the `status` (idle, pending, success, error), the `value` of the successful result, and any `error` that occurs. The `execute` function, returned by the hook, can be called to trigger the async operation. If `immediate` is true, it runs once on mount. This hook simplifies the common pattern of handling loading, success, and error states for any promise-based function.