Generate a React custom hook for asynchronous functions
- User
Generate a React custom hook for asynchronous functions
Assistant
Below is an example of a custom React hook designed to handle asynchronous functions. This hook, named
useAsync, will manage the loading state, error handling, and the data fetched or computed by your asynchronous operation. It's reusable across your React application, making it easier to handle async operations consistently.useAsync.jsjsximport { useState, useEffect } from 'react'; /** * Custom React Hook for managing asynchronous operations. * * @param {function} asyncFunction The asynchronous function to be executed. * @param {array} dependencies If present, the hook will re-run the asyncFunction when these change. * @param {object} options Optional: { initialData, retry, retryDelay } * - initialData: Initial data to display before the async operation completes. * - retry: Number of times to retry the async operation if it fails. * - retryDelay: Delay in milliseconds between retries. */ const useAsync = (asyncFunction, dependencies = [], options = {}) => { const { initialData = null, retry = 0, retryDelay = 500 } = options; // 500ms default delay const [status, setStatus] = useState('idle'); // idle | pending | success | error const [value, setValue] = useState(initialData); const [error, setError] = useState(null); const [retryCount, setRetryCount] = useState(0); // The async function wrapper to handle side-effects const execute = async () => { setStatus('pending'); setError(null); try { const response = await asyncFunction(); setValue(response); setStatus('success'); } catch (error) { setError(error); setStatus('error'); // Retry mechanism with delay if (retry > 0 && retryCount < retry) { setRetryCount(retryCount + 1); setTimeout(execute, retryDelay); // Retry after a delay } } }; // Run the effect when dependencies change useEffect(() => { if (asyncFunction) { execute(); } }, [asyncFunction, ...dependencies]); return { status, value, error, retryCount }; }; export default useAsync;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.