v4 regression: setQueryData triggers render after setState #4836
Send to my agentDescribe 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#
- Create a parent component
Outerwhich contains a useQuery hook and renders a child componentInner - Pass the child component the data from the query as a prop
- Call
setQueryDataandsetStatein the childInnercomponent. - Observe that the
Innercomponent renders before theOutercomponent, 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
ashaarmstrong(GitHub profile, opens in a new tab) changed the title
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 :(
Can you maybe explain why it is an issue in your app?
I'll close this as it's stale and there probably isn't much we can do on our end.
TkDodo closed this
TkDodo added labelsupstream
Sign in to join this conversation.
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: