You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
setState after awaited invalidation will sometimes render new state with previous query data #8815
It usually works, but under very carefully crafted conditions, there will be one render where the selected state is updated, but the query does not contain the new item.
If you click Add, you will see new items being added and selected. But in you check the console.logs, there is one render where we show an ERROR in which the item is selected but it is not added to the query result.
Steps to reproduce
This was very difficult to isolate.
In the sandbox I provide, you can see a lot of "unnecessary" code.
unnecessary code like const _ignored = new Uint8Array(..);
A seemsly unnecessary request (to a blob URL for easy reproduction)
Some wait() calls
An additional useQuery() is required too, subscribed to its isFetching property.
Removing any of them individually make the bug go away
So it seems it requires some careful timing and scheduling of tasks and microtasks for it to happen.
Expected behavior
If I update the cache and set some react state, I should not get a render with the state but not the cache updated.
How often does this bug happen?
Often
Screenshots or Videos
No response
Platform
MacOS: 15.3.1
Chrome: Version 134.0.6998.89 (Official Build) (arm64)
changed the title [-]setState after awaited invalidation will sometimes render stale data[/-][+]setState after awaited invalidation will sometimes render new state with previous query data[/+]on Mar 16, 2025
I have gone crazy with this issue for a few days now. Our complete stack uses many other different libraries that I thought could be interfering with react and react-query scheduling of tasks and microtasks.
But I managed to isolate it here.
I can continue trying to simplify the issue further and I can jump into the code. But hopefully some of you more familiar with the library internals have some ideas of where it could be coming from.
the invalidations aren’t batched together, so I can see this might yield back to react too early. Wrapping this with our batching mechanism also works:
Ah, my bad! I missed that part of the message in mobile. Thanks for taking the time to respond @TkDodo.
I have quickly updated the sandbox to use notifyManager. But, it seems, the issue is still happening. It throws the error sometimes, if I click add 2 or 3 times.
Batching would batch the renders of the both invalidateQueries right? I think it is fine for those renders to be separated (or batched), it should not matter. But I am seeing the result of the setState() before the result of first invalidateQuery.
Batching would batch the renders of the both invalidateQueries right?
yes, it wouldn’t batch with the react state update.
I just found this in your code:
const {
// Necessary to trigger the bug
isFetching: _isFetching,
} = useAnotherQuery();
by destructing isFetching, you’re subscribing your component to the isFetching flag, which will always change to true while the query is fetching. This means that when you do invalidation, your component will re-render with isFetching: true. Since this is at the root of your app, you might get another re-render of everything in this state before the mutation is finished. That’s an intermediate render where your selected item is not yet in the list.
This is specific to the isFetching flag (or the fetchStatus field) because it’s pretty much the only thing that will trigger a re-render when an invalidation is “starting”.
#4836 is a very similar issue. Maybe it is closer to the root cause.
The underyling react issue with useSyncExternalStore was marked as completed, not sure if it is supposed to be fixed in react 19, but the sandbox is still failing with react 19
App subscribes to a query List shows the result, and has a button to run a mutation, invalidate the query and set some local state as in the previous example
mutateAsync runs, mutation settles, and it run invalidateQuery.
Once the query finishes, the App QueryObserver is notified. However, the default scheduler is setTimeout(fn, 0)
Then invalidateQuery resolves. And we call setState, so a state update is scheduled with a microtask.
setState only affects the List component. React renders the List component renders before App, so useExternalStore from the app did not get the chance to be notified yet.
As a result, we see the local state before the query update
Here is a new codesandbox with a much much simplified reproduction:
What is the reason for the notify scheduler? can't we immediately call the subscription so useSyncExternalStore receives the update immediately and we let react do the scheduling? Is it needed for @tanstack/query batching?
Should queueMicrotask or an equivalent with MessageChannel if necessary for compatibility reasons be the default?
Thanks for the detailed analysis, I think you’re right on all accounts.
Setting the NotifyManager.setScheduler(queueMicrotask) solves the problem.
It has been on my list for the next major version so make queueMicrotask the default scheduling behaviour everywhere, as it seems to be the standard.
What is the reason for the notify scheduler? can't we immediately call the subscription so useSyncExternalStore receives the update immediately and we let react do the scheduling?
Our scheduling pre-dates useSyncExternalStore, and we’ve seen fewer intermediate re-renders with this approach. We also want to not rely on react’s behaviour, as our core is framework agnostic. Note that redux toolkit query has a similar optimization turned on per default, and they also default to queueMicrotask.
If you want to let react handle all the scheduling, setting the scheduler to:
notifyManager.setScheduler((cb) => cb());
should also work. I’ve tried this in your example and it does work, however, I get a lot of test failures internally if I do this, especially for those tests that check render count, so you might see more renders if you go that route. There are almost no failures with queueMicrotask though.
I encountered a related issue with this. when you mix imperative (sync) code interacting with the client + declarative React code, then React can read stale data. basically when a query is updated in sync (e.g. through setData), the observer gets notified after batch+schedule. however in case react rerenders before hand (e.g. through setState), then the observer has not updated yet. setting scheduler to fn => fn() solves this problem, but imho the observer should never return stale data when read, but should always "revalidate" on read, so stale reads can not happen.
Activity
[-]setState after awaited invalidation will sometimes render stale data[/-][+]setState after awaited invalidation will sometimes render new state with previous query data[/+]davazp commentedon Mar 16, 2025
I have gone crazy with this issue for a few days now. Our complete stack uses many other different libraries that I thought could be interfering with react and react-query scheduling of tasks and microtasks.
But I managed to isolate it here.
I can continue trying to simplify the issue further and I can jump into the code. But hopefully some of you more familiar with the library internals have some ideas of where it could be coming from.
TkDodo commentedon Mar 17, 2025
in this code, a race condition is expected because you don’t await the promise in
onSuccess:so the mutation will “finish” before the invalidation is done, and
setStatewill be called prematurely.in we change this to:
things consistently work fine.
Now in your reproduction, you also have:
the invalidations aren’t batched together, so I can see this might yield back to react too early. Wrapping this with our batching mechanism also works:
notifyManagercan be imported from"@tanstack/react-query"davazp commentedon Mar 17, 2025
@TkDodo sorry for the "sketch". But please checkout the codesandbox. I am awaiting the promises there as you can see:
I hand wrote the sketch to simplify the description because the reproduction is full of subtle details that have to be in place. I will update it.
TkDodo commentedon Mar 17, 2025
Yes, I also commented on the sandbox behaviour, see the part about batching.
davazp commentedon Mar 17, 2025
Ah, my bad! I missed that part of the message in mobile. Thanks for taking the time to respond @TkDodo.
I have quickly updated the sandbox to use
notifyManager. But, it seems, the issue is still happening. It throws the error sometimes, if I click add 2 or 3 times.Batching would batch the renders of the both invalidateQueries right? I think it is fine for those renders to be separated (or batched), it should not matter. But I am seeing the result of the setState() before the result of first invalidateQuery.
TkDodo commentedon Mar 17, 2025
yes, it wouldn’t batch with the react state update.
I just found this in your code:
by destructing
isFetching, you’re subscribing your component to theisFetchingflag, which will always change totruewhile the query is fetching. This means that when you do invalidation, your component will re-render withisFetching: true. Since this is at the root of your app, you might get another re-render of everything in this state before the mutation is finished. That’s an intermediate render where your selected item is not yet in the list.This is specific to the
isFetchingflag (or thefetchStatusfield) because it’s pretty much the only thing that will trigger a re-render when an invalidation is “starting”.davazp commentedon Mar 17, 2025
#4836 is a very similar issue. Maybe it is closer to the root cause.
The underyling react issue with
useSyncExternalStorewas marked as completed, not sure if it is supposed to be fixed in react 19, but the sandbox is still failing with react 19davazp commentedon Mar 17, 2025
Ok I think I now understand what is going on!
Consider two components:
Appsubscribes to a queryListshows the result, and has a button to run a mutation, invalidate the query and set some local state as in the previous exampleThe timeline looks like:
mutateAsyncruns, mutation settles, and it runinvalidateQuery.setTimeout(fn, 0)setState, so a state update is scheduled with a microtask.Listcomponent. React renders theListcomponent renders before App, souseExternalStorefrom the app did not get the chance to be notified yet.As a result, we see the local state before the query update
Here is a new codesandbox with a much much simplified reproduction:
https://codesandbox.io/p/sandbox/tanstack-query-usestate-after-mutation-forked-l43vcy
Setting the
NotifyManager.setScheduler(queueMicrotask)solves the problem.A few questions @TkDodo
What is the reason for the notify scheduler? can't we immediately call the subscription so
useSyncExternalStorereceives the update immediately and we let react do the scheduling? Is it needed for @tanstack/query batching?Should
queueMicrotaskor an equivalent withMessageChannelif necessary for compatibility reasons be the default?TkDodo commentedon Mar 18, 2025
Thanks for the detailed analysis, I think you’re right on all accounts.
It has been on my list for the next major version so make
queueMicrotaskthe default scheduling behaviour everywhere, as it seems to be the standard.Our scheduling pre-dates
useSyncExternalStore, and we’ve seen fewer intermediate re-renders with this approach. We also want to not rely on react’s behaviour, as our core is framework agnostic. Note that redux toolkit query has a similar optimization turned on per default, and they also default toqueueMicrotask.If you want to let react handle all the scheduling, setting the scheduler to:
should also work. I’ve tried this in your example and it does work, however, I get a lot of test failures internally if I do this, especially for those tests that check render count, so you might see more renders if you go that route. There are almost no failures with
queueMicrotaskthough.backbone87 commentedon Feb 21, 2026
I encountered a related issue with this. when you mix imperative (sync) code interacting with the client + declarative React code, then React can read stale data. basically when a query is updated in sync (e.g. through setData), the observer gets notified after batch+schedule. however in case react rerenders before hand (e.g. through setState), then the observer has not updated yet. setting scheduler to
fn => fn()solves this problem, but imho the observer should never return stale data when read, but should always "revalidate" on read, so stale reads can not happen.fix(ui): decide a press of Show more by the end of its own read (#677) (