JAVASCRIPT

React `useAsync` Hook for Managing Asynchronous Operations

A versatile React hook to manage the state (loading, error, data) of any asynchronous operation, simplifying data fetching and promise handling in components.

import { useState, useEffect, useCallback } from 'react';

// A generic async hook to handle loading, error, and value states for any promise.
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 passed asyncFunction and handles state updates.
  // It's wrapped in useCallback to prevent re-creation on every render if immediate is false.
  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, the caller will need to trigger it manually.
  useEffect(() => {
    if (immediate) {
      execute();
    }
  }, [execute, immediate]);

  return { execute, status, value, error };
}

export default useAsync;
How it works: The `useAsync` hook simplifies managing the state of any asynchronous operation, such as data fetching or complex calculations that return a Promise. It tracks the operation's `status` (idle, pending, success, error), its `value` (resolved data), and any `error` that occurs. This abstraction reduces boilerplate code in components, making it easier to display loading indicators, error messages, and fetched data consistently. It can be triggered immediately upon component mount or manually via the `execute` function.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs