Skip to content

useAsync

Tom Mitchelmore edited this page Aug 25, 2022 · 2 revisions

useAsync is a hook that manages the lifecycle states of an async function (callback). This is helpful for complicated components as it handles loading and errors for you.

This is intended to handle expensive computation - if you're data fetching you're probably looking for Tanstack Query or SWR.

Usage

import { useAsync } from 'react-multitool';

function Demo() {

  const someExpensiveComputation = async () => {
    await new Promise(resolve => setTimeout(resolve, 1000));
    return 'Hello World';
  }

  const { data, error, loading, execute } = useAsync(someExpensiveComputation);

  return (
    <div>
      {loading && <div>Loading...</div>}
      {error && <div>Error: {error.message}</div>}
      {data && <div>{data}</div>}
      <button onClick={execute}>Execute</button>
    </div>
  )

}

Reference

If using Typescript, you can use the generic <T> (defaults to any) to define the type of data - without this the return type will be inferred from the return value of the callback.

useAsync<T = any>(
  callback: () => Promise<T>,
  options?: UseAsyncOptions
  ): {
    execute: () => void;
    data: T | undefined;
    pending: boolean;
    error: Error | undefined;
}

Options (UseAsyncOptions)

Parameter Type Default Description
immediate boolean false If true, execute the callback immediately.
allowConcurrent boolean true If true, execute the callback even if the previous execution is still pending.
Clone this wiki locally