Skip to content

setState after awaited invalidation will sometimes render new state with previous query data #8815

Closed as not planned

Description

@davazp

Describe the bug

A have a code that, in essence, boils down a logic like the following (full repo with reproduction below):

function Component () {
  const itemsQuery = useQuery(...)
  const mutation = useMutation(.., onSuccess: async ()=>{
    return queryClient.invalidateQueries(...)
  });

  const [selected, setSelected] = useState(null);

  const handleAdd = async ()=>{
    await mutation.mutateAsync();
  }

  return <div>
    <button onClick={()=>{
        const result = await handleAdd();
        setSelect(result.id)
  }>Add</button>
    <ul>...list...</ul>
  </div>

}

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.

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/tanstack-query-usestate-after-mutation-vclmrm

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)
  • @tastack-query: 5.68.1

Tanstack Query adapter

react-query

TanStack Query version

5.68.1

TypeScript version

No response

Additional context

No response

Activity

  1. 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
  2. davazp commented on Mar 16, 2025

    @davazp
    Author

    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.

  3. TkDodo commented on Mar 17, 2025

    @TkDodo
    Collaborator

    in this code, a race condition is expected because you don’t await the promise in onSuccess:

      const mutation = useMutation(.., onSuccess: async ()=>{
        queryClient.invalidateQueries(...)
      });
    

    so the mutation will “finish” before the invalidation is done, and setState will be called prematurely.

    in we change this to:

    onSuccess() {
      return queryClient.invalidateQueries({ queryKey: ["items"] });
    }
    

    things consistently work fine.

    Now in your reproduction, you also have:

        async onSuccess() {
          return Promise.all([
            queryClient.invalidateQueries({ queryKey: ["another-query"] }),
            queryClient.invalidateQueries({ queryKey: ["items"] }),
          ]);
        },
    

    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:

        async onSuccess() {
          return notifyManager.batch(() =>
            Promise.all([
              queryClient.invalidateQueries({ queryKey: ["items"] }),
              queryClient.invalidateQueries({ queryKey: ["another-query"] }),
            ])
          );
        },
    

    notifyManager can be imported from "@tanstack/react-query"

  4. davazp commented on Mar 17, 2025

    @davazp
    Author

    @TkDodo sorry for the "sketch". But please checkout the codesandbox. I am awaiting the promises there as you can see:

      const mutation = useMutation({
        mutationKey: ["create"],
        mutationFn: async (name: string) => {
          return postItem(name);
        },
        async onSuccess() {
          return Promise.all([
            queryClient.invalidateQueries({ queryKey: ["another-query"] }),
            queryClient.invalidateQueries({ queryKey: ["items"] }),
          ]);
        },
      });

    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.

  5. TkDodo commented on Mar 17, 2025

    @TkDodo
    Collaborator

    But please checkout the codesandbox. I am awaiting the promises there as you can see

    Yes, I also commented on the sandbox behaviour, see the part about batching.

  6. davazp commented on Mar 17, 2025

    @davazp
    Author

    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.

  7. TkDodo commented on Mar 17, 2025

    @TkDodo
    Collaborator

    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”.

  8. davazp commented on Mar 17, 2025

    @davazp
    Author

    #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

  9. davazp commented on Mar 17, 2025

    @davazp
    Author

    Ok I think I now understand what is going on!

    Consider two components:

    App
      List
    

    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

    mutation.mutateAsync().then((result)=>{ setSelected(result.id) });

    The timeline looks like:

    1. User presses the button
    2. mutateAsync runs, mutation settles, and it run invalidateQuery.
    3. Once the query finishes, the App QueryObserver is notified. However, the default scheduler is setTimeout(fn, 0)
    4. Then invalidateQuery resolves. And we call setState, so a state update is scheduled with a microtask.
    5. 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:

    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 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?

  10. TkDodo commented on Mar 18, 2025

    @TkDodo
    Collaborator

    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.

  11. backbone87 commented on Feb 21, 2026

    @backbone87

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions