reactjsreact-query

useQuery prevent data fetching onClick


I am using the useQuery hook to fetch data from an endpoint which is successful, however, the endpoints seems to be called every time a click is made on the page. Here's what that looks like:

Hello world getting printed to the console when mouse is clicked on the page

P.S. I've omitted the actual function for testing purposes

const { data, refetch, isLoading } = useQuery({
    queryKey: "some-key",
    queryFn: () => console.log("Hello World")
  });

Every time I click the page, "Hello World" gets printed to the console. How do I prevent this from happening? Essentially, the fetch should happen only when the data is updated.


Solution

  • This is definitely due to the refetchOnWindowFocus: true default of react-query, which will refetch stale queries when a refetch occurs. Note that queries are always stale per default because staleTime defaults to zero.

    The best approach is usually to customize staleTime to your liking per resource.

    Also note that in React Query v5, we’ve switched to not listening to the focus event directly, but only the visibilitychange event, where clicking in the devtools and back to the page does not trigger a refetch.