Home / Articles

TanStack Query Basics: Queries, Caching, Mutations and Invalidation

Learn how useQuery, queryKey, staleTime, gcTime, useMutation and invalidation fit together to manage server state in React without hand-written fetch effects.

Publisher: REACTAPP.TOP7 min read1663 words

This article is published in English.

Sources: Started with React Query

TanStack Query, formerly React Query, manages data that comes from a server. The name changed because the library now works outside React too, in Svelte, Vue and Solid. A short way to describe it is a state manager for server state.

Server state versus client state

Server state is data that originates in a backend or an external API: users, products, posts, comments. It lives outside the application, so the app doesn't fully control it. It can change without the app knowing, it can go out of date and it can only be reached through an asynchronous request.

Client state belongs to the application itself. Whether a modal is open, for instance, exists only in the browser, as in const [isModalOpen, setIsModalOpen] = useState(false). Zustand, Redux and Jotai are the usual tools for that kind of state.

The manual approach and its cost

Without a library, fetching users usually starts with three pieces of state.

const [users, setUsers] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)

Then an effect does the loading.

useEffect(() => {
  async function fetchUsers() {
    try {
      setLoading(true)      const res = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      )      const data = await res.json()      setUsers(data)
    } catch (err) {
      setError(err)
    } finally {
      setLoading(false)
    }
  }  fetchUsers()

The users are fetched, stored in state, a loading flag is raised and errors are caught. As an app grows, this pattern repeats everywhere, and each copy has to handle loading and error states, caching, refetching, background refetching, synchronization and retries. Multiply that across a large codebase and the result is tangled code.

The same thing with a query

A single hook replaces the boilerplate.

function Users() {
  const {
    data,
    isLoading,
    error
  } = useQuery({
    queryKey: ["users"],
    queryFn: fetchUsers
  })

The component then branches on the status.

  if (isLoading) {
    return <p>Loading...</p>
  }  if (error) {
    return <p>Something went wrong</p>
  }  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>
          {user.name}
        </li>
      ))}
    </ul>
  )
}

TanStack Query takes over the infrastructure around server data. Its main advantage over useEffect plus useState is built-in caching. Once data arrives, it goes into a cache and can be reused later, which cuts unneeded API requests. Loading, success and error states are tracked automatically, so there's no logic to write and maintain by hand.

Setup

Install the package.

npm install @tanstack/react-query

Then create a QueryClient and provide it to the app.

const queryClient = new QueryClient();

root.render(
<QueryClientProvider client={queryClient}>
    <App />
</QueryClientProvider>
);

Reading data with useQuery

The useQuery hook handles reads, meaning anything that fetches server data. A basic call looks like this:

const { data,
isPending,
error } = useQuery({
 queryKey: ["users"],
 queryFn: fetchUsers
 })

It takes an options object, and two properties matter most: queryFn and queryKey.

The queryFn is what TanStack Query calls to get the data. It returns the data directly or as a Promise, and on failure it should throw or return a rejected Promise.

async function fetchUsers() {
  const res = await fetch("/api/users")

  if (!res.ok) {
    throw new Error("Failed to fetch users")
  }

  return res.json()
}

Then it plugs into the hook:

useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers
})

The queryKey uniquely identifies a query and its cached data. Variables used by the queryFn should generally appear in the key. For example, ["users"] could stand for all users, ["todo", 1] for the todo with ID 1 and ["products", "laptops"] for laptops.

The hook returns an object with the query's status (loading, error or success), the data and functions to refetch.

How the cache helps

This is where the library earns its place. Fetched data is stored automatically and reused to avoid redundant calls, which improves performance and shortens the time to display results.

Say Component A asks for ["users"]. TanStack Query fetches and caches the result. Later, Component B asks for the same key and the library notices the data is already cached. Rather than every component keeping its own copy, TanStack Query manages one cached copy of the server state. That's one of the biggest differences between plain fetch() and this library.

staleTime and gcTime

staleTime answers one question: how long should this data count as fresh?

useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
  staleTime: 60,000 // 60 seconds
})

With that setting, data is fresh for the first 60 seconds. After one minute it becomes stale, which allows a refetch to be triggered and a background refresh to happen. Stale doesn't mean deleted, though the data might be outdated. Once stale, it can be refetched when something triggers that, such as the window regaining focus or a component mounting.

Ignoring staleness leads to needless requests when users revisit a page.

User visits page
       ↓
Fetch users
       ↓
User navigates away
       ↓
User comes back
       ↓
Fetch users again

If nothing changed, the second request is wasted. A longer freshness window avoids it:

staleTime: 5 * 60 * 1000

That marks data as fresh for five minutes. Remember that staleTime controls freshness and is not a refetch interval.

There's also gcTime, the garbage collection time. It sets how long inactive, unobserved cached data stays in memory before being collected.

useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
  gcTime: 60000
})

To sum up, staleTime is how long data stays fresh, and gcTime is how long unused cache entries stick around. They solve different problems.

Refetching

Stale queries can refetch when a component mounts, the window regains focus or the network reconnects, and these behaviors are configurable. A manual refetch is available too.

const { refetch } = useQuery(...)
refetch()

Polling is possible as well.

useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
  refetchInterval: 30,000
})

The query then refetches roughly every 30 seconds while active. Refetching replaces stale data with fresh data from the backend.

Changing data with useMutation

Everything so far reads data. Creating, updating or deleting (POST, PUT, PATCH, DELETE) goes through the useMutation hook. As an example, here's creating a user. First comes the mutation function.

async function createUser(user) {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(user),
    }
  );

  if (!response.ok) {
    throw new Error("Failed to create user");
  }

  return response.json();
}

Next it's passed to useMutation.

import { useMutation } from "@tanstack/react-query";

function CreateUser() {
  const mutation = useMutation({
    mutationFn: createUser,
  });

  return (
    <button
      onClick={() =>
        mutation.mutate({
          name: "John Doe",
          email: "john@example.com",
        })
      }
      disabled={mutation.isPending}
    >
      {mutation.isPending ? "Creating..." : "Create User"}
    </button>
  );
}

export default CreateUser;

A button click triggers the mutation through mutation.mutate().

Button click
    ↓
mutation.mutate(user)
    ↓
createUser(user)
    ↓
POST request
    ↓
Server

Notice that createUser() is never called directly. The component calls mutation.mutate() and TanStack Query invokes the function.

Mutations carry status flags like queries do.

const {
  mutate,
  isPending,
  isSuccess,
  isError,
  error,
  data,
} = useMutation({
  mutationFn: createUser,
});

They drive the UI.

<button
  onClick={() => mutate({ userName: "delfina ghimire" })}
  disabled={isPending}
>
  {isPending ? "Creating..." : "Create user"}
</button>

Once mutate() runs, the mutation moves through several states:

  • isPending: the mutation is running.
  • isSuccess: it finished successfully.
  • isError: it failed.
  • data: the result of a successful mutation.
  • error: details when it fails.
  • mutate: the trigger, which accepts the variables for the mutation function.

That makes giving feedback during a create, update or delete straightforward.

The QueryClient and invalidation

The QueryClient is a central object that manages the cache and coordinates how queries and mutations behave. It was created earlier with new QueryClient(), and inside a component it's reached through useQueryClient(). It supports invalidating queries, updating cached data, removing cached data, resetting queries and prefetching. A typical call is queryClient.invalidateQueries({ queryKey: ["users"] }).

Invalidation matters most after mutations. When a mutation changes server data, related queries may hold outdated results, and invalidating them marks them stale so they can be refetched. Suppose the cache holds two users:

[
  { id: 1, userName: "delfina ghimire" },
  { id: 2, userName: "spiderman ghimire" },
]

A new user is then created.

mutation.mutate({
  userName: "ironman ghimire",
});

The server now has three users, but the cache still shows two. The ["users"] query can be marked stale. First the client is obtained:

const queryClient = useQueryClient();

Then the mutation invalidates on success.

const mutation = useMutation({
  mutationFn: createUser,
  onSuccess: () => {
    queryClient.invalidateQueries({
      queryKey: ["users"],
    });
  },
});

The flow runs like this:

Create Users (Mutation)
     ↓
Server data changes
     ↓
Invalidate ["users"]
     ↓
Query becomes stale
     ↓
Refetch
     ↓
UI gets fresh data

To keep the terms apart: invalidate marks cached data as stale, and refetch loads it again right away. Invalidating an active query will generally trigger an automatic refetch.

The whole picture

The pieces connect into one story:

  1. TanStack Query manages server data.
  2. Reading is done with useQuery.
  3. Fetched data lands in the query cache.
  4. staleTime decides when cached data counts as fresh.
  5. gcTime decides how long unused cache entries remain.
  6. Refetching decides when data is loaded again.
  7. Creating, updating and deleting go through useMutation.
  8. The QueryClient coordinates queries, mutations and the cache.
  9. Query invalidation signals that cached data is out of date.

With these relationships clear, the library gets much easier to reason about.