← Back to all snippets
JAVASCRIPT

Managing Async Operations with `useAsync`

A custom React hook for handling asynchronous operations like API calls, providing loading, error, and data states in a reusable pattern.

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

export const useAsync = (asyncFunction, immediate = true) => {
  const [status, setStatus] = useState('idle');
  const [value, setValue] = useState(null);
  const [error, setError] = useState(null);

  const execute = useCallback(() => {
    setStatus('pending');
    setValue(null);
    setError(null);
    return asyncFunction()
      .then(response => {
        setValue(response);
        setStatus('success');
      })
      .catch(error => {
        setError(error);
        setStatus('error');
      });
  }, [asyncFunction]);

  useEffect(() => {
    if (immediate) {
      execute();
    }
  }, [execute, immediate]);

  return { execute, status, value, error };
};
How it works: This `useAsync` hook encapsulates asynchronous logic, managing `status` ('idle', 'pending', 'success', 'error'), `value`, and `error` states. It accepts an `asyncFunction` and an `immediate` flag. If `immediate` is true, the function executes on mount. The `execute` function can also be called manually. It's ideal for abstracting data fetching or other async tasks, making components cleaner and more focused.

Need help integrating this into your project?

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

Hire DigitalCodeLabs