Search code examples
reactjsreact-query

React Query refetches despite the fact that staleTime is set to Infinity


export const useAllUsers = () =>
  useQuery<UserResponseDto[]>({
    queryKey: [QueryClientKeys.GET_ALL_USERS],
    queryFn: async () => {
      const response = await http.get<
        UserResponseDto[],
        AxiosResponse<UserResponseDto[]>
      >(`${API_BASE}/api/user/all`);
      return response.data;
    },
    staleTime: Infinity,
  });

The above query is problematic. It goes something like this - it fetches users on first mount, I leave that page (query hook is unmounted), and then 5 minutes later return to the same page and the refetch happens. Why is this happening?

I've tried setting cacheTime to Infinity and it seems to work. Is this the right way to handle this?

I'm using v4.


Solution

  • React Query has its own garbage collector and is always trying to free up memory on the client in the background by deleting unneeded querys results.

    You set the staleTime to infinite, which means that the result is never considered stale, but the moment you leave the page that uses the result and the cache time expires (which is 5 minutes by default) the garbage collector kicks in and clears the result away.

    If you now call the page again, query recognizes that it has no more result to it and executes the query again.

    So if you really only want to retrieve the data once at runtime and it should be valid forever, you really have to set the cache time to infinite.