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

ratios

v1.2.1

Published

A React hook library for managing axios requests, includes cancellation mechanism.

Readme

Ratios

A React hook library for managing axios requests, includes cancellation mechanism.

Installation

  • If you're using yarn: yarn add ratios
  • If you're using npm: npm install ratios --save

Demo

See live demo on Stackblitz.

For more information about why we should cancel a request before component unmounts, please see this article.

Basic usage

1. First, manage your axios requests in a proper way

// File: /src/apis/user.js
import axios from "axios";

const instance = axios.create({
  baseURL: "/api/users",
  headers: {
    "Content-Type": "application/json",
  },
  // ...
});

const UserAPI = {
  getAll: (config) => instance.get("", config),
  create: (data) => (config) => instance.post("", data, config),
  updateById: (id, data) => (config) => instance.put(`/${id}`, data, config),
  deleteById: (id) => (config) => instance.delete(`/${id}`, config),
};

export default UserAPI;

2. Import the "useAxiosRequest" hook from Ratios, and use one of the axios requests we just created as argument

import React from "react";
import { useAxiosRequest } from "ratios";
import UserAPI from "../apis/user";

const MyComponent = () => {
  const getUsersRequest = useAxiosRequest(UserAPI.getAll);

  return (
    <div>
      {getUsersRequest.isLoading ? (
        "Loading..."
      ) : (
        <ol>
          {getUsersRequest.data.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ol>
      )}
    </div>
  );
};

export default MyComponent;

And that's it! The hook will cancel the request for you when the component unmounts.

Advanced usage

1. With custom config (e.g, query parameters)

import React, { useState } from "react";
import { useAxiosRequest } from "ratios";
import UserAPI from "../apis/user";

const MyComponent = () => {
  const [filter, setFilter] = useState({
    name: "",
    age: 5,
  });

  const getUsersRequest = useAxiosRequest((cancelTokenConfig) =>
    UserAPI.getByQuery({
      ...cancelTokenConfig,
      params: filter,
    })
  );

  // Your other codes
};

2. With custom arguments (e.g, create user)

import React, { useState } from "react";
import { useAxiosRequest } from "ratios";
import UserAPI from "../apis/user";

const MyComponent = () => {
  const [form, setForm] = useState({
    name: "John Doe",
    age: 10,
  });

  const createUserRequest = useAxiosRequest(UserAPI.create(form), {
    defaultIsLoading: false,
    immediate: false,
    onError: handleError,
  });

  const handleSubmitClick = async () => {
    const createdUser = await createUserRequest.execute();
    console.log("Created user: ", createdUser);
  };

  const handleError = (error) => {
    console.log("Something went wrong.");
    console.error(error);
  };

  // Your other codes
};

3. useCancelTokenSource hook

If you just want to apply cancellation mechanism to your existing app, you can use the "useCancelTokenSource" hook.

import { useCancelTokenSource } from "ratios";

const MyComponent = () => {
  const cancelTokenSource = useCancelTokenSource();

  const myFunction = async () => {
    try {
      const { data } = await myAPI.getSomething({
        cancelToken: cancelTokenSource.token,
      });
      console.log(data);
    } catch (error) {
      if (cancelTokenSource.isCancelError(error)) {
        console.log("Request is cancelled.");
      } else {
        throw error;
      }
  };

  // Your other codes
};

The request will be cancelled automatically when component unmounts.

API

1. Properties for useAxiosRequest()

| key | Type | Description | | --------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | isLoading | boolean | If the request is still going on. | | data | <T = any> | The data property returned from axios response. | | setData | (callback: (prevData: T) => T) | The function to update data. | | executed | boolean | If the request has been executed. | | execute | () => Promise<T> | Execute the request manually. If the isLoading property is still true, then it will NOT execute the request. Will return the data property from axios response if success. |

2. Options for useAxiosRequest()

| key | Type | Required | Default Value | Description | | ---------------- | --------------------- | -------- | ------------- | ----------------------------------------------------------------------------- | | defaultIsLoading | boolean | false | true | The default value of request.isLoading. | | defaultData | any | false | undefined | The default value of request.data. | | immediate | boolean | false | true | If the request should be executed immediately after the component is mounted. | | cancelPrevious | boolean | false | true | If the previous request should be cancelled before executing a new one. | | onSuccess | (data: T) => any | false | undefined | Function to execute when API is successfully executed. | | onError | (error: any) => any | false | undefined | Function to execute when an error occurred during API execution. | | onCancelled | (error: any) => any | false | undefined | Function to execute when the request is cancelled. |

3. Properties for useCancelTokenSource()

| key | Type | Description | | ------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------- | | token | CancelToken | The cancel token. | | cancel | () => CancelToken | undefined | Return next token if repeatable is true, else return undefined. | | isCancelError | (value: any) => boolean | Use this method to check if an error is thrown due to cancellation. This method equals to axios.isCancel. |

4. Options for useCancelTokenSource()

| key | Type | Required | Default Value | Description | | ---------- | --------- | -------- | ------------- | ---------------------------------------- | | repeatable | boolean | false | true | If the token can be used multiple times. |