npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-use-stateful-promise

v1.2.1

Published

A React hook for managing async operations with status, data and cancellation.

Readme

UseStatefulPromise react hook

npm version build dependencies codecov license

A tiny, no-dependencies, fully type-safe React hook for running async functions with built-in status management, cancellation, reset, state synchronization and optional side effects.

Features

  • 🚀 Run any async function (fetch or any other library or custom)
  • 👁️ Track async operation status idle | loading | success | error
  • 🧠 Stores data & error inside hook state
  • ❌ Supports cancellation (prevents state updates after cancel)
  • 🔄 Supports reset (cancels and restores initial state)
  • 🔒 Race-condition safe (only the latest call can update state)
  • 🪶 Lightweight (no dependencies)
  • 🔧 Fully typed with TypeScript generics
  • ⚛️ React Compiler compatible (no need for useCallback)

Demo

Live Demo on GitHub Pages

The demo showcases:

  • Running successful async operations
  • Error handling on rejected async operations
  • Canceling in-flight promises
  • Resetting state
  • Ensuring no race conditions (Only the latest invocation resolves — stale promises are ignored automatically.)
  • Visualizing status transitions (IDLE → LOADING → SUCCESS / ERROR)

You can also explore the full demo source code inside the /demo folder of the repository.

Install

npm:

npm install react-use-stateful-promise

yarn:

yarn add react-use-stateful-promise

Usage

TypeScript (with types):

import { useStatefulPromise, Status } from "react-use-stateful-promise";

import { User } from "./types";

function Example() {
  const fetchUser = async (id: number) => {
    const res = await fetch(`/api/user/${id}`);
    return res.json();
  };

  const { status, data, error, run, cancel, reset } = useStatefulPromise<
    User,
    [number]
  >(fetchUser, {});

  return (
    <div>
      <button onClick={() => run(1)}>Load user</button>

      {status === Status.LOADING && <p>Loading...</p>}
      {status === Status.ERROR && <p>Error: {error?.message}</p>}
      {status === Status.SUCCESS && <pre>{JSON.stringify(data.name)}</pre>}

      <button onClick={cancel}>Cancel</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

JavaScript (no types):

import { useStatefulPromise, Status } from "react-use-stateful-promise";

function Example() {
  const fetchUser = async (id) => {
    const res = await fetch(`/api/user/${id}`);
    return res.json();
  };

  const { status, data, error, run, cancel, reset } = useStatefulPromise(
    fetchUser,
    {}
  );

  return (
    <div>
      <button onClick={() => run(1)}>Load user</button>

      {status === Status.LOADING && <p>Loading...</p>}
      {status === Status.ERROR && <p>Error: {error?.message}</p>}
      {status === Status.SUCCESS && <pre>{JSON.stringify(data.name)}</pre>}

      <button onClick={cancel}>Cancel</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

API Reference

const { status, data, run, cancel, reset } = useStatefulPromis(
  asyncFunction,
  initialData,
  {
    // optional callbacks for each action
    onSuccess: (newData) => newData,
    onError: (error) => error,
    onCancel: () => null,
    onReset: () => null,
  }
);

Returned values

| Name | Type | Description | | ------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | status | Status ("IDLE" \| "LOADING" \| "ERROR" \| "SUCCESS") | The current state of the async call. | | data | T | The resolved value from the async function. | | error | Error \| null | The caught error if the async function rejects. | | run(...args) | (...args: Args) => Promise<T> | Runs the async function with the given arguments, updates state accordingly. Returns the underlying promise for chaining. | | cancel() | () => void | Cancels the current pending async call and resets the hook to IDLE. Prevents updates from the canceled promise. | | reset() | () => void | Fully resets state, clears data and error, and cancels any pending promise. |

Parameters

| Parameter | Type | Required | Description | | ----------------------- | ----------------------------- | -------- | ----------------------------------------------------------------- | | asyncFunction | (…args: Args) => Promise<T> | ✔️ Yes | Any function returning a Promise. The hook manages its lifecycle. | | initialData | T | ✔️ Yes | Initial value for data. | | options | object | ✖️ No | Optional callbacks triggered on success, error, cancel, or reset. | | options.onSuccess | (data: T) => void | ✖️ No | Called when the async function resolves. | | options.onError | (error: Error) => void | ✖️ No | Called when the async function rejects. | | options.onCancel | () => void | ✖️ No | Called when the async operation is cancelled. | | options.onReset | () => void | ✖️ No | Called when reset() is invoked. |

Contributing

Contributions are welcome and appreciated, be it opening issues, opening pull requests or just asking questions.

The repository includes the demo environment for easier testing of the hook.

To start working, fork and clone the repository locally and then

cd react-use-stateful-promise

npm i # Install deps

npm run test # Run tests
npm run dev # Spin up demo environment

The hook code is located in the /lib folder.

The demo code is located in the /demo folder.

LICENSE

MIT