Skip to Content
ohooks

useAsyncTask

Manages the manual execution, cancellation, and state of an asynchronous task with AbortSignal support.

Loading preview...

The useAsyncTask hook runs an asynchronous task on demand, tracks its pending state and result, and passes an AbortSignal to the task so in-flight work can be cancelled.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useAsyncTask.json

Usage

Examples

Passing Arguments

Arguments passed to run are forwarded to the task after the context object.

Cancellation

Call abort to cancel the in-flight task. The signal passed to the task is aborted, so fetch and other signal-aware APIs stop immediately.

API Reference

AsyncTaskContext

Context object passed as the first argument to the task.

Property
Specification
signalrequired
object
Signal used to abort the in-flight task

UseAsyncTaskOptions

Configuration options for the task.

Property
Specification
initialData?
TResult
Initial value for data before the first run (and after reset)
resetDataOnRun?
uniondefault:false
Reset data back to initialData when a new run starts
onSuccess?
function
Callback invoked when the task resolves successfully
onError?
function
Callback invoked when the task throws a non-abort error
onAbort?
function
Callback invoked when the task is aborted

UseAsyncTaskReturn

Task state and controls returned by the hook.

Property
Specification
status
AsyncTaskStatus
Current execution status of the task
data
union
Resolved data from the latest successful run
error
union
Error from the latest failed run, or null
isIdle
union
true when the task has not been run yet or was reset
isPending
union
true while the task is currently executing
isSuccess
union
true when the latest run completed successfully
isError
union
true when the latest run failed with an error
isAborted
union
true when the latest run was aborted
run
function
Executes the task with the given arguments (aborts any in-flight run)
abort
function
Aborts the currently running task
reset
function
Aborts any in-flight run and resets state back to idle