beautiful-react-hooks, react-async-hook, react-query, react-use, and usehooks-ts are all npm packages that provide reusable React hooks to simplify common frontend tasks. These libraries aim to reduce boilerplate and improve code quality by encapsulating logic for state management, side effects, browser APIs, and asynchronous operations. While they share overlapping goals, they differ significantly in scope, architecture, and intended use cases โ from general-purpose utility hooks (react-use, usehooks-ts) to specialized async and data-fetching solutions (react-async-hook, react-query). beautiful-react-hooks focuses on declarative event handling and lifecycle abstractions.
Managing state, side effects, and async logic in React apps often leads to repetitive useEffect and useState patterns. The libraries beautiful-react-hooks, react-async-hook, react-query, react-use, and usehooks-ts each offer prebuilt hooks to reduce this boilerplate โ but they solve different problems. Letโs compare them through real-world scenarios.
beautiful-react-hooks provides hooks like useEvent, useWindowResize, and useGeolocation that automatically manage event listener setup/teardown.
// beautiful-react-hooks: auto-cleanup event listener
import { useEvent } from 'beautiful-react-hooks';
function ClickTracker() {
const onClick = useEvent('click', (event) => {
console.log('Clicked at', event.clientX, event.clientY);
});
// No manual useEffect or removeEventListener needed
return <div onClick={onClick}>Track clicks</div>;
}
react-use and usehooks-ts also offer similar hooks, but require more explicit control:
// react-use: useClick
import { useClick } from 'react-use';
function ClickTracker() {
const ref = useRef(null);
useClick(ref, () => console.log('Clicked'));
return <div ref={ref}>Track clicks</div>;
}
// usehooks-ts: useEventListener
import { useEventListener } from 'usehooks-ts';
function ClickTracker() {
const handleClick = () => console.log('Clicked');
useEventListener('click', handleClick);
return <div>Track clicks</div>;
}
react-async-hook and react-query donโt focus on DOM events โ theyโre purely for async and data logic.
For basic async calls (e.g., form submission), react-async-hook wraps functions and exposes loading, error, and result:
// react-async-hook
import { useAsyncCallback } from 'react-async-hook';
function LoginForm() {
const login = useAsyncCallback(async (credentials) => {
return await api.login(credentials);
});
if (login.loading) return <Spinner />;
if (login.error) return <Error msg={login.error.message} />;
return <form onSubmit={() => login.execute({ user, pass })} />;
}
react-query goes further โ it treats async results as server state with caching, deduplication, and background refetching:
// react-query
import { useQuery, useMutation } from '@tanstack/react-query';
function UserProfile({ userId }) {
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId)
});
const mutation = useMutation({
mutationFn: updateUser,
onSuccess: () => {
// Invalidate and refetch user data
queryClient.invalidateQueries(['user', userId]);
}
});
return <div>{isLoading ? '...' : data.name}</div>;
}
react-use and usehooks-ts donโt provide dedicated async state hooks. Youโd typically combine useState/useEffect manually or use useAsync from react-use (which is basic):
// react-use: simple async
import { useAsync } from 'react-use';
const { value, loading, error } = useAsync(() => fetchUser(id), [id]);
beautiful-react-hooks has no async utilities.
react-use and usehooks-ts shine here with dozens of hooks for browser features:
// react-use
import { useLocalStorage, useNetwork, useMedia } from 'react-use';
const [darkMode, setDarkMode] = useLocalStorage('theme', 'light');
const isOnline = useNetwork().online;
const isMobile = useMedia('(max-width: 768px)');
// usehooks-ts
import { useLocalStorage, useNetwork, useMediaQuery } from 'usehooks-ts';
const [darkMode, setDarkMode] = useLocalStorage('theme', 'light');
const isOnline = useNetwork().online;
const isMobile = useMediaQuery('(max-width: 768px)');
react-query and react-async-hook donโt cover these. beautiful-react-hooks includes some (e.g., useGeolocation), but far fewer than the utility-focused libraries.
Only react-query provides automatic caching, stale-while-revalidate, pagination, and mutation rollback:
// react-query handles cache keys, deduplication, background updates
const { data } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
staleTime: 1000 * 60 // 1 min
});
All other libraries treat async results as local component state. If two components fetch the same data, theyโll make two network requests unless you build your own cache.
usehooks-ts is built from the ground up in TypeScript with strict types:
// usehooks-ts: fully typed
const [value, setValue] = useLocalStorage<string>('key', 'default');
react-use also offers strong TypeScript support, though some hooks have looser inference.
react-query has excellent TypeScript integration, especially around query keys and mutation variables.
react-async-hook and beautiful-react-hooks support TypeScript but with less comprehensive typing in edge cases.
As of 2024, all five packages are actively maintained with recent releases. None are deprecated.
| Feature / Package | beautiful-react-hooks | react-async-hook | react-query | react-use | usehooks-ts |
|---|---|---|---|---|---|
| DOM Event Helpers | โ Rich | โ | โ | โ Good | โ Good |
| Async State Management | โ | โ Basic | โ Advanced (caching, mutations) | โ
Basic (useAsync) | โ |
| Browser API Hooks | โ ๏ธ Limited | โ | โ | โ Extensive | โ Extensive |
| Server-State Focus | โ | โ | โ Yes | โ | โ |
| TypeScript-First | โ ๏ธ Partial | โ ๏ธ Partial | โ Excellent | โ Strong | โ Strict |
react-query is the industry standard.beautiful-react-hooks reduces boilerplate.react-async-hook is lightweight and sufficient.react-use (larger ecosystem) or usehooks-ts (cleaner TS, smaller API).Donโt mix react-query with the others for data fetching โ it solves that problem completely. But combining react-query with usehooks-ts (for useDebounce, useLocalStorage, etc.) is a common and effective pattern in production apps.
Choose react-async-hook when you want a lightweight, focused solution for managing async function states (loading, error, result) without external dependencies. Itโs ideal for wrapping simple API calls or async computations in components, but lacks advanced features like caching, retries, or background refetching.
Choose beautiful-react-hooks if you need clean, declarative hooks for DOM events (like clicks, scrolls, or window resizing) with built-in cleanup and dependency management. Itโs well-suited for interactive UIs where you want to avoid manual useEffect boilerplate for event listeners, but it doesnโt handle data fetching or caching.
Choose react-query for robust server-state management โ especially when your app relies heavily on data fetching from APIs. It provides automatic caching, background updates, pagination, mutations, and devtools out of the box. Use it when you need to minimize network requests and keep UI data synchronized with backend sources.
Choose react-use if you need a broad collection of high-quality, battle-tested hooks covering browser APIs (e.g., localStorage, media queries), sensors (e.g., mouse, network status), and utilities (e.g., previous value, timeout). Itโs excellent as a general-purpose hook toolkit but doesnโt specialize in async or server-state management.
Choose usehooks-ts when you prefer TypeScript-first, minimal, and well-documented implementations of common custom hooks (like useLocalStorage, useDebounce, or useWindowSize). Itโs a solid alternative to react-use with stricter type safety and simpler internals, but similarly avoids complex async orchestration.
This tiny library only does one thing, and does it well.
Don't expect it to grow in size, it is feature complete:
useAsync)useAsyncCallback)useAsyncAbortable + AbortController)| Lib | min | min.gz |
|---|---|---|
| React-Async-Hook | ||
| SWR | ||
| React-Query | ||
| React-Async | ||
| Use-HTTP | ||
| Rest-Hooks |
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.
The ability to inject remote/async data into a React component is a very common React need. Later we might support Suspense as well.
import { useAsync } from 'react-async-hook';
const fetchStarwarsHero = async id =>
(await fetch(`https://swapi.dev/api/people/${id}/`)).json();
const StarwarsHero = ({ id }) => {
const asyncHero = useAsync(fetchStarwarsHero, [id]);
return (
<div>
{asyncHero.loading && <div>Loading</div>}
{asyncHero.error && <div>Error: {asyncHero.error.message}</div>}
{asyncHero.result && (
<div>
<div>Success!</div>
<div>Name: {asyncHero.result.name}</div>
</div>
)}
</div>
);
};
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.
import { useAsyncCallback } from 'react-async-hook';
const AppButton = ({ onClick, children }) => {
const asyncOnClick = useAsyncCallback(onClick);
return (
<button onClick={asyncOnClick.execute} disabled={asyncOnClick.loading}>
{asyncOnClick.loading ? '...' : children}
</button>
);
};
const CreateTodoButton = () => (
<AppButton
onClick={async () => {
await createTodoAPI('new todo text');
}}
>
Create Todo
</AppButton>
);
Examples are running on this page and implemented here (in Typescript)
yarn add react-async-hook
or
npm install react-async-hook --save
If you use ESLint, use this react-hooks/exhaustive-deps setting:
// .eslintrc.js
module.exports = {
// ...
rules: {
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': [
'error',
{
additionalHooks: '(useAsync|useAsyncCallback)',
},
],
},
};
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 by useRef).
const StarwarsHero = ({ id }) => {
// Create a constant debounced function (created only once per component instance)
const debouncedFetchStarwarsHero = useConstant(() =>
AwesomeDebouncePromise(fetchStarwarsHero, 1000)
);
// Simply use it with useAsync
const asyncHero = useAsync(debouncedFetchStarwarsHero, [id]);
return <div>...</div>;
};
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:
const searchStarwarsHero = async (
text: string,
abortSignal?: AbortSignal
): Promise<StarwarsHero[]> => {
const result = await fetch(
`https://swapi.dev/api/people/?search=${encodeURIComponent(text)}`,
{
signal: abortSignal,
}
);
if (result.status !== 200) {
throw new Error('bad status = ' + result.status);
}
const json = await result.json();
return json.results;
};
const useSearchStarwarsHero = () => {
// Handle the input text state
const [inputText, setInputText] = useState('');
// Debounce the original search async function
const debouncedSearchStarwarsHero = useConstant(() =>
AwesomeDebouncePromise(searchStarwarsHero, 300)
);
const search = useAsyncAbortable(
async (abortSignal, text) => {
// If the input is empty, return nothing immediately (without the debouncing delay!)
if (text.length === 0) {
return [];
}
// Else we use the debounced api
else {
return debouncedSearchStarwarsHero(text, abortSignal);
}
},
// Ensure a new request is made everytime the text changes (even if it's debounced)
[inputText]
);
// Return everything needed for the hook consumer
return {
inputText,
setInputText,
search,
};
};
And then you can use your hook easily:
const SearchStarwarsHeroExample = () => {
const { inputText, setInputText, search } = useSearchStarwarsHero();
return (
<div>
<input value={inputText} onChange={e => setInputText(e.target.value)} />
<div>
{search.loading && <div>...</div>}
{search.error && <div>Error: {search.error.message}</div>}
{search.result && (
<div>
<div>Results: {search.result.length}</div>
<ul>
{search.result.map(hero => (
<li key={hero.name}>{hero.name}</li>
))}
</ul>
</div>
)}
</div>
</div>
);
};
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 responsability to wire the abort signal appropriately.
const StarwarsHero = ({ id }) => {
const asyncHero = useAsyncAbortable(
async (abortSignal, id) => {
const result = await fetch(`https://swapi.dev/api/people/${id}/`, {
signal: abortSignal,
});
if (result.status !== 200) {
throw new Error('bad status = ' + result.status);
}
return result.json();
},
[id]
);
return <div>...</div>;
};
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
const StarwarsHero = ({ id }) => {
const asyncHero = useAsync(fetchStarwarsHero, [id], {
setLoading: state => ({ ...state, loading: true }),
});
return <div>...</div>;
};
If your params are not changing, yet you need to refresh the data, you can call execute()
const StarwarsHero = ({ id }) => {
const asyncHero = useAsync(fetchStarwarsHero, [id]);
return <div onClick={() => asyncHero.execute()}>...</div>;
};
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.
const asyncSomething = useAsync(() => fetchSomething(state.a), [
state.a,
state.b,
]);
Here, only state.a will trigger a refetch, despite b being passed to the async fetch function.
const asyncSomething = useAsync(() => fetchSomething(state.a, state.b), [
state.a,
]);
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:
const asyncSomething = useAsync(async () => {
const payload = buildFetchPayload(state);
const result = await fetchSomething(payload);
return result;
}), [state.a, state.b, state.whateverNeedToTriggerRefetch]);
You can also use useAsyncCallback to decide yourself manually when a fetch should be done:
const asyncSomething = useAsyncCallback(async () => {
const payload = buildFetchPayload(state);
const result = await fetchSomething(payload);
return result;
}));
// Call this manually whenever you need:
asyncSomething.execute();
Use a lib that adds retry feature to async/promises directly.
MIT
Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.