Skip to content
Source
Sign inSign up
TanStack/query

v4 regression: setQueryData triggers render after setState #4836

Send to my agent
Closedashaarmstrong(GitHub profile, opens in a new tab) opened this issue 4 comments

Describe the bug

I've run into a problem with setQueryData which has introduced a few logic bugs in an app I'm working on. The issue is that when calling both setState and setQueryData in a nested component that receives its data via props from a query in a parent component, the call to setState triggers a re-render with stale query data even after setQueryData is called. Only after that render completes is a render in the parent component triggered with the data provided to setQueryData. This behaviour differs if the useQuery hook is in the child component, in which case there is only one render which has the correct data.

This behaviour was unexpected and differs from swr. swr triggers a render in the parent component first and has consistent behaviour whether the query hook is in the parent or the child component.

This also appears to be a regression in v4 (assuming it isn't documented somewhere). Using react-query v3.39.2 the parent component renders first.

Please let me know if I'm missing something :)

Your minimal, reproducible example

https://codesandbox.io/s/react-query-setquerydata-order-sub7yi?file=/src/App.js

Steps to reproduce

  1. Create a parent component Outer which contains a useQuery hook and renders a child component Inner
  2. Pass the child component the data from the query as a prop
  3. Call setQueryData and setState in the child Inner component.
  4. Observe that the Inner component renders before the Outer component, thus using query data from before setQueryData was called

Expected behavior

As a user, I expected the parent component to render before the child and pass down the data set via setQueryData

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

macOS Chrome

TanStack Query version

v4.22.0

TypeScript version

No response

Additional context

No response

  1. I think this is another report of the batching problem with useSyncExternalStore, which we use under the hood in v4 (but not in v3). Have a look at this open issue in React:

  2. That does look like it could be the cause. Thanks for finding that!

    It does put me in a bit of a predicament though. We're still using React 16, so the upstream fixes are unlikely to land for us for a long time. Could this be worked around in react-query? If not we might have to downgrade to v3 :(

  3. Can you maybe explain why it is an issue in your app?

  4. I'll close this as it's stale and there probably isn't much we can do on our end.

  5. TkDodo closed this

  6. TkDodo added labelsupstream

Sign in to join this conversation.