Weird behavior with "useIsMutating" hook
I was playing with this hook and wondering if this is intended:
I fired multiple mutations ( let's say 6 ) with the same scope.id ( to make them queue ) and with onSuccess callback that just logs what useIsMutating returns.
So I am getting a log every time a mutation from the queue is finished, but all my logs are "0" and only the last one logs "1".
If I log the same value outside of the callback I get values from 6 to 1, which is what I would expect.
Codesandbox: https://codesandbox.io/p/sandbox/nv7mlx

2 Replies
absent-sapphire•2mo ago
this is just how closures work in JS, so it's a "stale closure" issue. The callback gets created when on the first render, so it closes over the value from
useIsMutating from that time. I have a blogpost on closures and react: https://tkdodo.eu/blog/hooks-dependencies-and-stale-closuresHooks, Dependencies and Stale Closures
Let's demystify what stale closures are in combination with react hooks with the help of the analogy of taking a photo ...
absent-sapphire•2mo ago
to read the latest value, just do
queryClient.isMutating() inside the callback instead of useIsMutating