react-querytanstacktanstackreact-query

Why does the browser trigger a refetch of values in useQuery from TanStack when it is refocused?


I'm using the useQuery hook from the React Query library in my React application to fetch data from my server. However, I've noticed that whenever I switch away from the browser tab and then come back to it, the useQuery hook triggers a refetch of the data.

I would like to understand why this is happening and how I can prevent it from happening.


Solution

  • Because react-query refetches stale queries when a window focus event happens, and per default, all queries are considered stale.

    https://tanstack.com/query/v4/docs/react/guides/window-focus-refetching

    The best way to work with this and similar situations is to specify an appropriate staleTime for your resource.