query icon indicating copy to clipboard operation
query copied to clipboard

onSuccess callback in useQuery fires twice

Open sshmyg opened this issue 5 years ago • 24 comments

Describe the bug useQuery call one by one for same endpoint but for different components (one component should be child for other and parent should render child only on isLoading === false);

To Reproduce Steps to reproduce the behavior (visit link for details): https://codesandbox.io/s/vigilant-swartz-ox5p9?file=/src/App.js

Expected behavior onSuccess should be called once.

Screenshots First load image

Desktop (please complete the following information):

  • OS: mac os 11.1
  • Browser: chrome
  • Version: 89.0.4389.82

sshmyg avatar Mar 15 '21 10:03 sshmyg

Unless I'm missing something, useEffect with a dependency of the data (or query) still triggers multiple times.

yes, true. If you want it to only happen once, you'd need to dispatch from within the queryFn.

TkDodo avatar Mar 11 '23 09:03 TkDodo

Interesting read, I've been using react-query for a long time but I just learned this behaviour today.

I was having component A & B that just happen to be mounted in the same page (because certain condition is met) and both calling useQuery with the same queryKey, but useQuery on component B is conditionally disabled, both having their own unique onSuccess handler and was thinking that it's a bug because onSuccess on component B still got called even if it's enabled: false.

Perhaps it's not that clear on the useQuery docs section? but I don't know how to improve it to make sure user understand this exact behaviour, or probably it's useful to just refer them to read this issue instead, because it was helpful for me to understand the whole thing by reading all the explanation from @TkDodo

Thank you so much!

alvin883 avatar Mar 21 '23 09:03 alvin883

because onSuccess on component B still got called even if it's enabled: false.

we're discussing to change this behaviour here:

  • https://github.com/TanStack/query/issues/4827

TkDodo avatar Mar 21 '23 10:03 TkDodo

I totally agree @TkDodo opinion

  • component 1 mounts, data is fetched, onSuccess is called, data is immediately stale.
  • now component 2 mounts (conditionally, because component 1 is no longer loading). this triggers a background refetch, because data is stale.

key point is because data is stale.

This is a natural and natural phenomenon.

If you don't like this phenomenon, you can specify even a little staleTime. in QueryClient

Basically, it's because of the state batch update of react, because the state of isLoading changes sequentially, and the child is conditionally rendered😁

okinawaa avatar Apr 14 '23 14:04 okinawaa