7

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The doc link is fine but the best way to deal with is probably to set refetchOnWindowFocus: false, either globally of per-query, as stated in the documentation you linked.
I kinda disagree. Window focus refetching is a great default behaviour, it's just that refetching all queries on every window focus is not what most people expect. If you set staleTime, you'll only see a refetch if the query isn't fresh anymore. Example: User has a screen open (e.g. issue tracker), switches tabs, goes to twitter for 20 minutes, then comes back. An automatic refetch here assures that people don't need to hard reload the page - they can trust that what they see is reasonably up to date.
3

You can disable this feature on a per endpoint basis using the refetchOnWindowFocus prop

useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  refetchOnWindowFocus: false,
})

if you really dont need this feature you can disable it when setting up your queryclient.

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false, // default: true
    },
  },
})

refs:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.