react-async-hook

React hook to handle any async operation in React components, and prevent r...

README

React-Async-Hook

NPM Build Status

This tiny library only does one thing, and does it well.


Sponsor


ThisWeekInReact.com: the best newsletter to stay up-to-date with the React ecosystem:
ThisWeekInReact.com banner


Don't expect it to grow in size, it is feature complete:

- Handle fetches (useAsync)
- Handle mutations (useAsyncCallback)
- Handle cancellation (useAsyncAbortable + AbortController)
- Platform agnostic
- Works with any async function, not just backend API calls, not just fetch/axios...
- Very good, native, Typescript support
- Small, no dependency
- Rules of hooks: ESLint find missing dependencies
- Refetch on params change
- Can trigger manual refetch
- Options to customize state updates
- Can mutate state after fetch
- Returned callbacks are stable



Small size


- Way smaller than popular alternatives
- CommonJS + ESM bundles
- Tree-shakable

Libminmin.gz
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
**Suspend-React**[![](https://img.shields.io/bundlephobia/min/suspend-react.svg)](https://bundlephobia.com/package/suspend-react)[![](https://img.shields.io/bundlephobia/minzip/suspend-react.svg)](https://bundlephobia.com/package/suspend-react)
**React-Async-Hook**[![](https://img.shields.io/bundlephobia/min/react-async-hook.svg)](https://bundlephobia.com/package/react-async-hook)[![](https://img.shields.io/bundlephobia/minzip/react-async-hook.svg)](https://bundlephobia.com/package/react-async-hook)
**SWR**[![](https://img.shields.io/bundlephobia/min/swr.svg)](https://bundlephobia.com/package/swr)[![](https://img.shields.io/bundlephobia/minzip/swr.svg)](https://bundlephobia.com/package/swr)
**React-Query**[![](https://img.shields.io/bundlephobia/min/react-query.svg)](https://bundlephobia.com/package/react-query)[![](https://img.shields.io/bundlephobia/minzip/react-query.svg)](https://bundlephobia.com/package/react-query)
**React-Async**[![](https://img.shields.io/bundlephobia/min/react-async.svg)](https://bundlephobia.com/package/react-async)[![](https://img.shields.io/bundlephobia/minzip/react-async.svg)](https://bundlephobia.com/package/react-async)
**Use-HTTP**[![](https://img.shields.io/bundlephobia/min/use-http.svg)](https://bundlephobia.com/package/use-http)[![](https://img.shields.io/bundlephobia/minzip/use-http.svg)](https://bundlephobia.com/package/use-http)
**Rest-Hooks**[![](https://img.shields.io/bundlephobia/min/rest-hooks.svg)](https://bundlephobia.com/package/rest-hooks)[![](https://img.shields.io/bundlephobia/minzip/rest-hooks.svg)](https://bundlephobia.com/package/rest-hooks)


Things we don't support (by design):


- stale-while-revalidate
- refetch on focus / resume
- caching
- polling
- request deduplication
- platform-specific code
- scroll position restoration
- SSR
- router integration for render-as-you-fetch pattern

You can build on top of this little lib to provide more advanced features (using composition), or move to popular full-featured libraries like SWR or React-Query.

Use-case: loading async data into a component


The ability to inject remote/async data into a React component is a very common React need. Later we might support Suspense as well.

  1. ```tsx
  2. import { useAsync } from 'react-async-hook';

  3. const fetchStarwarsHero = async id =>
  4.   (await fetch(`https://swapi.dev/api/people/${id}/`)).json();

  5. const StarwarsHero = ({ id }) => {
  6.   const asyncHero = useAsync(fetchStarwarsHero, [id]);
  7.   return (
  8.     <div>
  9.       {asyncHero.loading && <div>Loading</div>}
  10.       {asyncHero.error && <div>Error: {asyncHero.error.message}</div>}
  11.       {asyncHero.result && (
  12.         <div>
  13.           <div>Success!</div>
  14.           <div>Name: {asyncHero.result.name}</div>
  15.         </div>
  16.       )}
  17.     </div>
  18.   );
  19. };
  20. ```

Use-case: injecting async feedback into buttons


If you have a Todo app, you might want to show some feedback into the "create todo" button while the creation is pending, and prevent duplicate todo creations by disabling the button.

Just wire useAsyncCallback to your onClick prop in your primitive AppButton component. The library will show a feedback only if the button onClick callback is async, otherwise it won't do anything.

  1. ```tsx
  2. import { useAsyncCallback } from 'react-async-hook';

  3. const AppButton = ({ onClick, children }) => {
  4.   const asyncOnClick = useAsyncCallback(onClick);
  5.   return (
  6.     <button onClick={asyncOnClick.execute} disabled={asyncOnClick.loading}>
  7.       {asyncOnClick.loading ? '...' : children}
  8.     </button>
  9.   );
  10. };

  11. const CreateTodoButton = () => (
  12.   <AppButton
  13.     onClick={async () => {
  14.       await createTodoAPI('new todo text');
  15.     }}
  16.   >
  17.     Create Todo
  18.   </AppButton>
  19. );
  20. ```

Examples


Examples are running on this page and implemented here (in Typescript)

Install


yarn add react-async-hook
or

npm install react-async-hook --save

ESLint


If you use ESLint, use this [react-hooks/exhaustive-deps](https://github.com/facebook/react/blob/master/packages/eslint-plugin-react-hooks/README.md#advanced-configuration) setting:

  1. ```ts
  2. // .eslintrc.js
  3. module.exports = {
  4.   // ...
  5.   rules: {
  6.     'react-hooks/rules-of-hooks': 'error',
  7.     'react-hooks/exhaustive-deps': [
  8.       'error',
  9.       {
  10.         additionalHooks: '(useAsync|useAsyncCallback)',
  11.       },
  12.     ],
  13.   },
  14. };
  15. ```

FAQ


How can I debounce the request


It is possible to debounce a promise.

I recommend awesome-debounce-promise, as it handles nicely potential concurrency issues and have React in mind (particularly the common use-case of a debounced search input/autocomplete)

As debounced functions are stateful, we have to "store" the debounced function inside a component. We'll use for that use-constant (backed byuseRef).

  1. ```tsx
  2. const StarwarsHero = ({ id }) => {
  3.   // Create a constant debounced function (created only once per component instance)
  4.   const debouncedFetchStarwarsHero = useConstant(() =>
  5.     AwesomeDebouncePromise(fetchStarwarsHero, 1000)
  6.   );

  7.   // Simply use it with useAsync
  8.   const asyncHero = useAsync(debouncedFetchStarwarsHero, [id]);

  9.   return <div>...</div>;
  10. };
  11. ```

How can I implement a debounced search input / autocomplete?


This is one of the most common use-case for fetching data + debouncing in a component, and can be implemented easily by composing different libraries.
All this logic can easily be extracted into a single hook that you can reuse. Here is an example:

  1. ```tsx
  2. const searchStarwarsHero = async (
  3.   text: string,
  4.   abortSignal?: AbortSignal
  5. ): Promise<StarwarsHero[]> => {
  6.   const result = await fetch(
  7.     `https://swapi.dev/api/people/?search=${encodeURIComponent(text)}`,
  8.     {
  9.       signal: abortSignal,
  10.     }
  11.   );
  12.   if (result.status !== 200) {
  13.     throw new Error('bad status = ' + result.status);
  14.   }
  15.   const json = await result.json();
  16.   return json.results;
  17. };

  18. const useSearchStarwarsHero = () => {
  19.   // Handle the input text state
  20.   const [inputText, setInputText] = useState('');

  21.   // Debounce the original search async function
  22.   const debouncedSearchStarwarsHero = useConstant(() =>
  23.     AwesomeDebouncePromise(searchStarwarsHero, 300)
  24.   );

  25.   const search = useAsyncAbortable(
  26.     async (abortSignal, text) => {
  27.       // If the input is empty, return nothing immediately (without the debouncing delay!)
  28.       if (text.length === 0) {
  29.         return [];
  30.       }
  31.       // Else we use the debounced api
  32.       else {
  33.         return debouncedSearchStarwarsHero(text, abortSignal);
  34.       }
  35.     },
  36.     // Ensure a new request is made everytime the text changes (even if it's debounced)
  37.     [inputText]
  38.   );

  39.   // Return everything needed for the hook consumer
  40.   return {
  41.     inputText,
  42.     setInputText,
  43.     search,
  44.   };
  45. };
  46. ```

And then you can use your hook easily:

  1. ```tsx
  2. const SearchStarwarsHeroExample = () => {
  3.   const { inputText, setInputText, search } = useSearchStarwarsHero();
  4.   return (
  5.     <div>
  6.       <input value={inputText} onChange={e => setInputText(e.target.value)} />
  7.       <div>
  8.         {search.loading && <div>...</div>}
  9.         {search.error && <div>Error: {search.error.message}</div>}
  10.         {search.result && (
  11.           <div>
  12.             <div>Results: {search.result.length}</div>
  13.             <ul>
  14.               {search.result.map(hero => (
  15.                 <li key={hero.name}>{hero.name}</li>
  16.               ))}
  17.             </ul>
  18.           </div>
  19.         )}
  20.       </div>
  21.     </div>
  22.   );
  23. };
  24. ```

How to use request cancellation?


You can use the useAsyncAbortable alternative. The async function provided will receive (abortSignal, ...params) .

The library will take care of triggering the abort signal whenever a new async call is made so that only the last request is not cancelled.
It is your responsibility to wire the abort signal appropriately.

  1. ```tsx
  2. const StarwarsHero = ({ id }) => {
  3.   const asyncHero = useAsyncAbortable(
  4.     async (abortSignal, id) => {
  5.       const result = await fetch(`https://swapi.dev/api/people/${id}/`, {
  6.         signal: abortSignal,
  7.       });
  8.       if (result.status !== 200) {
  9.         throw new Error('bad status = ' + result.status);
  10.       }
  11.       return result.json();
  12.     },
  13.     [id]
  14.   );

  15.   return <div>...</div>;
  16. };
  17. ```

How can I keep previous results available while a new request is pending?


It can be annoying to have the previous async call result be "erased" everytime a new call is triggered (default strategy).
If you are implementing some kind of search/autocomplete dropdown, it means a spinner will appear everytime the user types a new char, giving a bad UX effect.
It is possible to provide your own "merge" strategies.
The following will ensure that on new calls, the previous result is kept until the new call result is received

  1. ```tsx
  2. const StarwarsHero = ({ id }) => {
  3.   const asyncHero = useAsync(fetchStarwarsHero, [id], {
  4.     setLoading: state => ({ ...state, loading: true }),
  5.   });
  6.   return <div>...</div>;
  7. };
  8. ```

How to refresh / refetch the data?


If your params are not changing, yet you need to refresh the data, you can call execute()

  1. ```tsx
  2. const StarwarsHero = ({ id }) => {
  3.   const asyncHero = useAsync(fetchStarwarsHero, [id]);

  4.   return <div onClick={() => asyncHero.execute()}>...</div>;
  5. };
  6. ```

How to handle conditional fetch?


You can enable/disable the fetch logic directly inside the async callback. In some cases you know your API won't return anything useful.

  1. ```tsx
  2. const asyncSearchResults = useAsync(async () => {
  3.   // It's useless to call a search API with an empty text
  4.   if (text.length === 0) {
  5.     return [];
  6.   } else {
  7.     return getSearchResultsAsync(text);
  8.   }
  9. }, [text]);
  10. ```

How to have better control when things get fetched/refetched?


Sometimes you end up in situations where the function tries to fetch too often, or not often, because your dependency array changes and you don't know how to handle this.

In this case you'd better use a closure with no arg define in the dependency array which params should trigger a refetch:

Here, both state.a and state.b will trigger a refetch, despite b is not passed to the async fetch function.

  1. ```tsx
  2. const asyncSomething = useAsync(() => fetchSomething(state.a), [
  3.   state.a,
  4.   state.b,
  5. ]);
  6. ```

Here, only state.a will trigger a refetch, despite b being passed to the async fetch function.

  1. ```tsx
  2. const asyncSomething = useAsync(() => fetchSomething(state.a, state.b), [
  3.   state.a,
  4. ]);
  5. ```

Note you can also use this to "build" a more complex payload. Using useMemo does not guarantee the memoized value will not be cleared, so it's better to do:

  1. ```tsx
  2. const asyncSomething = useAsync(async () => {
  3.   const payload = buildFetchPayload(state);
  4.   const result = await fetchSomething(payload);
  5.   return result;
  6. }), [state.a, state.b, state.whateverNeedToTriggerRefetch]);
  7. ```

You can also use useAsyncCallback to decide yourself manually when a fetch should be done:

  1. ```tsx
  2. const asyncSomething = useAsyncCallback(async () => {
  3.   const payload = buildFetchPayload(state);
  4.   const result = await fetchSomething(payload);
  5.   return result;
  6. }));

  7. // Call this manually whenever you need:
  8. asyncSomething.execute();
  9. ```

How to support retry?


Use a lib that adds retry feature to async/promises directly.

License


MIT

Hire a freelance expert


Looking for a React/ReactNative freelance expert with more than 5 years production experience?
Contact me from my website or with Twitter.