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-query-ease

v1.0.0

Published

Typed Axios + TanStack React Query API clients in a few lines — useQuery/useMutation hooks, auto cache invalidation, single-flight token refresh, and streaming (SSE/LLM) hooks for React and Next.js.

Readme

react-query-ease

npm version npm downloads bundle size types license

Typed Axios + TanStack React Query API clients in a few lines. Create one client per service, then call api.useQuery / api.useMutation with no repeated Axios boilerplate, query functions, or manual cache invalidation.

Features

  • 🧩 One client per service. createApiClient({ baseURL }) gives you useQuery, useMutation, and plain get/post/put/patch/delete helpers.
  • 🔁 Auto cache invalidation. keyToInvalidate: ["todos"] refetches queries after a successful mutation, or build the keys from the response: (todo, vars) => [["todo", vars.id]].
  • 🚀 Prefetching, SSR and Suspense. api.queryOptions() returns the exact { queryKey, queryFn } the hook uses, for prefetchQuery, Next.js HydrationBoundary, useSuspenseQuery, useQueries and setQueryData.
  • 🔐 Single-flight token refresh. createAuthInterceptor attaches tokens and refreshes once when several requests get a 401 at the same time, then retries the queued requests.
  • 🌊 Streaming hooks. useStream streams chunked and SSE responses, such as LLM or AI chat output, and shares the same auth refresh.
  • 🦺 TypeScript-first. Generic TData / TError / TVariables, a select that can change the data's type, and your registered defaultError (e.g. AxiosError) used by every hook.
  • ⚛️ Works with React and Next.js. Ships ESM and CJS, tree-shakeable with sideEffects: false.

Why not just TanStack Query + Axios?

TanStack Query handles caching, not HTTP: you still write a query function for every endpoint, an Axios instance, invalidation logic and token refresh, in every app. react-query-ease is that layer, written once, tested, and built on top of TanStack Query, so you keep everything it gives you.

With TanStack Query + Axios:

const http = axios.create({ baseURL: "/api" });

const useTodos = (page: number) =>
  useQuery({
    queryKey: ["todos", { page }],
    queryFn: ({ signal }) =>
      http.get<Todo[]>("/todos", { params: { page }, signal }).then((r) => r.data),
  });

const useCreateTodo = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (todo: NewTodo) => http.post<Todo>("/todos", todo).then((r) => r.data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  });
};

With react-query-ease:

const api = createApiClient({ baseURL: "/api" });

const useTodos = (page: number) =>
  api.useQuery<Todo[]>({ url: "/todos", key: ["todos"], params: { page } });

const useCreateTodo = () =>
  api.useMutation<Todo, unknown, NewTodo>({ url: "/todos", method: "POST", keyToInvalidate: ["todos"] });

What you stop writing by hand:

| | TanStack Query + Axios | react-query-ease | |---|---|---| | Query function per endpoint | You write it | Built from url, method and params | | params in the query key | Easy to forget, which serves stale pages | Added for you | | Cancellation on unmount | Pass signal yourself, every time | On by default | | Invalidate after a mutation | useQueryClient + onSuccess | keyToInvalidate: ["todos"] | | Unwrapping response.data | Every call | Done for you | | Prefetch, SSR, useSuspenseQuery | Rebuild the same key and query function again | api.queryOptions({ ... }), the same object the hook uses | | Token refresh on 401 | Write your own interceptor, queue and retry | createAuthInterceptor: one refresh for many concurrent 401s, then retries | | Streaming (SSE, LLM output) | Not covered; hand-roll fetch + a reader | useStream, sharing the same auth and refresh |

Nothing is hidden: every TanStack Query option (staleTime, enabled, select, …) and every Axios option (headers, timeout, …) still works on the same hook, and useQueryClient, devtools and invalidateQueries work as usual.

When to use it

TanStack Query gives you caching, background refetching, retries and request deduplication. react-query-ease adds the HTTP layer on top: the Axios client, query functions, cache keys, invalidation and token refresh. Use the two together when:

  • Your app talks to one or more REST/JSON APIs and has more than a handful of endpoints, so writing a query function and key for each one is real repetition.
  • You want Axios features, such as interceptors, baseURL, default headers, timeouts and typed errors with AxiosError.
  • Your API uses access and refresh tokens. createAuthInterceptor handles the 401 → refresh → retry flow, including many requests failing at once.
  • Mutations should refresh lists, for example creating a todo refetches ["todos"], without wiring useQueryClient into every hook.
  • You stream responses, such as LLM or AI chat output over SSE, and want streaming to share the same client, auth and refresh as your other requests.
  • You're on React or Next.js client components and want typed hooks per service, with one client per backend, for example authApi, billingApi.

When you don't need it:

  • Your backend has an OpenAPI spec: a code generator such as Orval can generate typed hooks for you.
  • You only call one or two endpoints: plain TanStack Query is fine.
  • You use GraphQL: use a GraphQL client such as Apollo or urql, or TanStack Query with a GraphQL fetcher.
  • You fetch only on the server, in React Server Components or route handlers, and never on the client: React Query's hooks run only in client components. (Prefetching on the server to hydrate client components is supported; see Prefetching, SSR and TanStack's own hooks.)

Claude Code skill

The repo includes an AI agent skill that sets up react-query-ease for you: API clients, typed hooks, auth interceptors and streaming.

Claude Code plugin (Claude Code 2.1.275 or later):

/plugin install react-query-ease --marketplace dibyajyoti79/react-query-ease

On older versions, add the marketplace first, then install:

/plugin marketplace add dibyajyoti79/react-query-ease
/plugin install react-query-ease@react-query-ease

Any agent (Claude Code, Cursor, Copilot, Codex and others), with the skills CLI (Node.js 22.20 or later):

npx skills add dibyajyoti79/react-query-ease

Add -g to install it for all your projects. Update it later with npx skills update.

The skill runs on its own when you ask your agent about data fetching, React Query or Axios setup. In Claude Code you can also run it directly with /react-query-ease.

Install

npm install react-query-ease axios @tanstack/react-query

Requires @tanstack/react-query 5, axios 1.21.1 or later and React 18 or later.

Quick example

import { createApiClient } from "react-query-ease";

const api = createApiClient({
  baseURL: "https://api.example.com",
});

const useTodos = () => {
  const query = api.useQuery({
    url: "/todos",
    method: "GET",
    key: ["todos"],
    // All Axios config props (headers, timeout, etc.) and React Query options (staleTime, enabled, etc.) can be passed directly
  });

  return {
    todos: query.data ?? [],
    isLoadingTodos: query.isLoading,
    ...query,
  };
};

const useCreateTodo = () => {
  const mutation = api.useMutation({
    url: "/todos",
    method: "POST",
    keyToInvalidate: ["todos"],
    // All Axios config props and React Query options can be passed directly
  });

  return {
    createTodo: mutation.mutate,
    isCreatingTodo: mutation.isPending,
    ...mutation,
  };
};

// For dynamic URLs in mutations (e.g., `/todos/${id}`), use a function:
const useUpdateTodo = () => {
  const mutation = api.useMutation({
    url: (variables) => `/todos/${variables.id}`, // Dynamic URL from variables
    method: "PATCH",
    keyToInvalidate: ["todos"],
  });

  return {
    updateTodo: mutation.mutate,
    isUpdatingTodo: mutation.isPending,
    ...mutation,
  };
};

function TodoList() {
  const { todos, isLoadingTodos } = useTodos();
  const { createTodo, isCreatingTodo } = useCreateTodo();

  if (isLoadingTodos) return <p>Loading...</p>;

  return (
    <>
      <button
        disabled={isCreatingTodo}
        onClick={() => createTodo({ title: "Buy milk" })}
      >
        Add todo
      </button>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </>
  );
}

Want the full CRUD + folder structure walkthrough? Check examples/todo-crud.md. Need interceptor reference? See examples/interceptors.md. For native streaming, check the Streaming Guide.

Prefetching, SSR and TanStack's own hooks

api.queryOptions(args) takes the same arguments as api.useQuery and returns the exact { queryKey, queryFn, ...options } the hook builds, params included in the key. Pass it to anything in TanStack Query:

const todoQuery = (id: number) =>
  api.queryOptions<Todo>({ key: ["todos", id], url: `/todos/${id}` });

await queryClient.prefetchQuery(todoQuery(1));          // prefetch / Next.js SSR + HydrationBoundary
const todo = await queryClient.ensureQueryData(todoQuery(1));
queryClient.setQueryData(todoQuery(1).queryKey, updated);

const { data } = useSuspenseQuery(todoQuery(1));
const results = useQueries({ queries: ids.map(todoQuery) });

Next.js App Router. Keep the client and the query builders in a file without "use client", so Server Components can import them:

// lib/api/queries.ts (no "use client")
export const todosQuery = () => api.queryOptions<Todo[]>({ key: ["todos"], url: "/todos" });

// app/todos/page.tsx (Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query";

export default async function TodosPage() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery(todosQuery());
  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <Todos /> {/* "use client": useQuery(todosQuery()) or api.useQuery with the same args */}
    </HydrationBoundary>
  );
}

On the server, baseURL must be absolute, and a token getter that reads localStorage won't work there. Forward cookies or headers yourself, or use a separate server client. Set a staleTime above 0 on the client so hydrated data isn't refetched straight away.

Dynamic invalidation

keyToInvalidate can be a function of the response and the variables:

api.useMutation<Todo, AxiosError, UpdateInput>({
  url: ({ id }) => `/todos/${id}`,
  method: "PATCH",
  keyToInvalidate: (todo, vars) => [["todos", vars.id], ["lists", todo.listId]],
});

Types

  • select can change the data's shape. The third generic is the selected type: api.useQuery<Todo[], AxiosError, number>({ ..., select: (todos) => todos.length }). Without explicit generics it's inferred from select: select: (todos: Todo[]) => todos.map((t) => t.title) gives data: string[] | undefined.
  • The error type follows React Query's default. Register your error type once and every hook uses it:
declare module "@tanstack/react-query" {
  interface Register {
    defaultError: AxiosError;
  }
}

Request helpers

Outside of hooks, every client also has plain request helpers. Each one resolves to the response body (response.data).

| Helper | Forms | |---|---| | api.get(url, config?) | Same as Axios | | api.delete(url, config?) | Same as Axios. A body goes in config.data | | api.post / api.put / api.patch | (url, data, config), the Axios form, or (url, config) with the body in config.data | | api.request(config) | Any request |

await api.post("/todos", { title: "Buy milk" }, { timeout: 5000 }); // Axios form
await api.post("/todos", { data: { title: "Buy milk" } });          // config form

Watch out: with only two arguments, the second one is the config, not the body. api.post("/todos", { title }) sends no body. TypeScript flags this, and in development the client logs a warning. Use the 3-argument form, or put the body in data.

Built-in auth interceptor helper

import { createApiClient, createAuthInterceptor } from "react-query-ease";

const tokens = {
  access: null as string | null,
  refresh: null as string | null,
};

const authInterceptor = createAuthInterceptor({
  getAccessToken: () => tokens.access,
  getRefreshToken: () => tokens.refresh,
  refreshTokens: async () => {
    const result = await fetch("/auth/refresh", {
      method: "POST",
      body: JSON.stringify({ refresh_token: tokens.refresh }),
    }).then((res) => res.json());

    tokens.access = result.accessToken;
    tokens.refresh = result.refreshToken;

    return result;
  },
});

export const secureApi = createApiClient({
  baseURL: "/api",
  configure: authInterceptor,
});

createAuthInterceptor wires up access-token headers, coalesces simultaneous refreshes, retries queued requests with the fresh token, and allows you to plug in logout/error handling via the options object. If your refresh call goes through the same client, mark it with skipAuth: true. Otherwise its own 401 would wait on the refresh that is already running:

let api: ReturnType<typeof createApiClient>;

api = createApiClient({
  baseURL: "/api",
  configure: createAuthInterceptor({
    getAccessToken: () => tokens.access,
    refreshTokens: () =>
      api.post<{ accessToken: string }>(
        "/auth/refresh",
        { refresh_token: tokens.refresh },
        { skipAuth: true }
      ),
    setTokens: (t) => {
      tokens.access = t.accessToken;
    },
  }),
});

A pending refresh is rejected after refreshTimeoutMs (default 30000; 0 disables it), so requests fail instead of hanging.

Options

| Option | Where | Default | What it does | |---|---|---|---| | paramsInKey | createApiClient, useQuery | true | Appends params to the query key, so each set of params is cached separately. Queries without params are unaffected. | | cancelable | createApiClient | true | Passes React Query's AbortSignal to Axios, so cancelQueries() and unmounting abort in-flight requests. | | axios | useQuery, useMutation | — | Axios config merged last. Use it for any Axios option you want to set explicitly. | | keyToInvalidate | useMutation | — | Keys to invalidate after success: a key, a string, an array of them, or (data, variables) => keys. | | body | useMutation | — | (variables) => body. Builds the request body. Without it, variables are sent as the body (except for GET/HEAD) unless data is set. | | skipAuth | any request, stream() | false | Skips the auth interceptor: no token is attached and a 401 doesn't trigger a refresh. | | refreshTimeoutMs | createAuthInterceptor | 30000 | Rejects a refresh that takes longer than this. |

Migrating to 1.0

1.0 is the first stable release. Full notes, with the reasons for each change, are in the changelog.

Breaking changes

| Change | What to do | |---|---| | TanStack Query v4 is no longer supported (peer range is now ^5.0.0) | Upgrade to v5 first with TanStack's migration guide and codemod. | | React 18+ is required | Upgrade React (TanStack Query v5 requires it). | | axios is a peer dependency (^1.21.1) | npm 7+ installs it for you. With pnpm or yarn: pnpm add axios / yarn add axios. If your app has an older axios, upgrade it: every version before 1.20.0 has security advisories. | | error is typed with React Query's default error (Error, or your registered defaultError) instead of unknown | Register AxiosError (see Types), or pass unknown as the second generic. | | A failed stream rejects with an AxiosError instead of a fetch Response error | Read the body from error.response.data; error.response.status works as before. | | Streams go through the Axios instance and its interceptors | To skip an interceptor for streams, check config.responseType === "stream". | | v4 option names (cacheTime, useErrorBoundary, keepPreviousData, isDataEqual, suspense) are sent to Axios | Use gcTime, throwOnError, placeholderData: keepPreviousData, structuralSharing, useSuspenseQuery. They already did nothing on v5. | | Private instance.__authOptions / __queueRefresh are gone | Keep your own reference to the auth interceptor options. | | SimpleApiClient type removed | Use ReturnType<typeof createApiClient>. |

New in 1.0 (no changes needed): api.queryOptions() for prefetching, SSR and Suspense; keyToInvalidate as a function; select that can change the data's type; a fix for a stale 401 starting a second token refresh.

Upgrading from 0.3.x? Also read the 0.5.0 notes for the two behaviour changes and their opt-outs.