Sergey Karlinsky
Sergey Karlinsky

Reputation: 116

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.

Upvotes: 4

Views: 6800

Answers (2)

J D
J D

Reputation: 174

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:

Upvotes: 1

TkDodo
TkDodo

Reputation: 28833

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.

Upvotes: 7

Related Questions