iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😶‍🌫️

[TanStack Query] Thinking about useQuery and useMutation from the perspective of React Effects

に公開
2025/12/30

Tanstack Query has gained immense support as a state management solution for asynchronous operations.
In this article, I will consider the proper use of useQuery versus useMutation in data fetching triggered by user interactions.

First, let's think about useQuery as having the nature of a React Effect.
The official React documentation explains Effects as follows:

Effects let you specify side effects that are caused by rendering itself, rather than by a particular event.
Reference: https://react.dev/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events

useQuery is triggered by a component render and synchronizes with external data. This behavior can be considered to fall exactly under "side effects caused by rendering itself."

Furthermore, the difference between Effects and event handlers is explained as follows:

If you’re not sure whether some code should be in an Effect or an event handler, ask yourself why this code needs to run. Use Effects only for code that should run because the component was displayed to the user.
Reference: https://react.dev/learn/you-might-not-need-an-effect#sharing-logic-between-event-handlers

Based on this, useQuery corresponds to "code that should run because the component was displayed." On the other hand, for processes triggered by a specific user interaction, such as "fetching data when a user clicks a button," I thought that using useMutation might be more appropriate, even for GET requests.

Below is an implementation example considering a case where data is fetched from the server and displayed when a button is pressed.

When using useQuery
const useTodo = () => {
  return useQuery({
    queryKey: ["todo"],
    queryFn: fetcher,
    enabled: false,
  });
};

export const Component = () => {
  const { refetch, isFetching, data } = useTodo();
  const handleClick = () => refetch();

  return (
    <div>
      <button onClick={handleClick}>Fetch!</button>
      <div>
        {isFetching ? (
          <p>loading...</p>
        ) : (
          <>
            {data?.map((d) => (
              <div key={d.id}>
                {d.id}: {d.title}
              </div>
            ))}
          </>
        )}
      </div>
    </div>
  );
};

What should be noted is that enabled is specified in the useQuery options.
When the enabled option is set to false, useQuery will not automatically execute data fetching when the component renders. Instead, you can control data fetching by executing refetch.

In this case, since data needs to be fetched when the button is clicked, using useMutation for data fetching in response to user interaction makes the intent of the processing clearer than suppressing the fetch at render time with enabled: false.

When using useMutation
const useTodo = () => {
  return useMutation({
    mutationFn: fetcher,
  });
};

export const Component = () => {
  const { data, isPending, mutate } = useTodo();
  const handleClick = () => mutate();

  return (
    <div>
      <button onClick={handleClick}>Fetch!</button>
      ...

However, when using useMutation, you need to be aware that the fetched data will not be shared across components via the cache.

It is important to use useQuery and useMutation appropriately by leveraging their respective characteristics. I recommend making the best choice for your application after considering data reusability, automatic revalidation, and caching strategies.

If you have any opinions or areas for improvement, please let me know in the comments or elsewhere.

Discussion