useAsyncRunner
A custom React hook to execute async functions with built-in state management for loading, success, failure, data, and error states—all fully type-safe.
How To Use
Setup
- Define your asynchronous function (
action
). - Pass it to the hook via the
action
parameter. - Destructure
run
,isPending
,isSuccess
,isFailure
,data
, anderror
from the hook.
Features
- Built-in state flags:
isPending
,isSuccess
,isFailure
- Automatically captures
data
anderror
- Fully generic and type-safe
- Reset state on each run
- Lightweight and SSR-compatible
Always pass a stable action
reference (e.g. useCallback
) to avoid
unnecessary re-renders.
API
Example
Below is a complete example that fetches a post by ID using JSONPlaceholder and demonstrates how to handle loading, success, and error states.