Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading