QueryClient.clear does not trigger a rerender immediately #7761
Send to my agentDescribe the bug#
Very short version:
Calling QueryClient.clear does not immediatelly trigger a rerender to the component that uses the useQuery hook.
Longer version:
In the repro example we have
- 2 routes/pages,
/logoutand/dashboard - A component
AuthProviderthat checks if the user is authenticated, and if they are it fetches the user data, using theuseUserhook, and passes it down as context. It also passes down 2 functions,loginandlogout, each of which makes use ofmutateAsyncfromuseLoginanduseLogouthooks respectively. - An accompanying hook called
useAuththat provides the context ofAuthProvider - A hook, which is called in each page, called
useAuthCheckwhich redirects the user to/dashboardif they are currently on/logoutand user data exists (userisAuthenticated) or redirects the user to/logoutif they are currently on/dashboardand no user data exists (user!isAuthenticated) - A call to
QueryClient.clearinside theonSuccessof theuseLogouthook
What is actually be happening
(READ THE WHAT IS SUPPOSED TO BE HAPPENING FIRST)
- We are on
/dashboardand the user clicks the logout button - User logs out,
QueryClient.clear()andhistory.replace('/logout')are called - The page for
/logoutrenders, due tolocationchanging internally inBrowserRouter - The
useAuthCheckhook callsuseAuthwhich returnsisAuthenticated: true(becauseAuthProviderhas not yet rerendered) - Since we are on
/logoutandisAuthenticated: truethe effect inuseAuthCheckredirects us back to/dashboard - Since
AuthProviderrerenders, it now passes the correct context down and it's what theuseAuthhook should provide when called. - The page for
/dashboardrenders - The
useAuthCheckhook callsuseAuthwhich now returnsisAuthenticated: false - Since we are on
/dashboardandisAuthenticated: falsethe effect inuseAuthCheckredirects us back to/logout - Nothing else happens, we stay on
/logoutas logged out users.
Your minimal, reproducible example#
https://stackblitz.com/edit/vitejs-vite-cwizyh?file=src%2Fproviders%2FAuthProvider.tsx&view=editor
Steps to reproduce#
- open up the preview of the example repo in its own tab so that yu can use the react devtools
- open up the dev console
- click on login
- enable breakpoints and click logout
- notice how the
AuthProvideris not immediately rerendering after theQueryClient.clear(), leading to a back and forth between/logoutand/dashboard
If you go into the code of AuthProvider and comment in the setToken that are commented out and try to reproduce the above behaviour, you will now notice that it works correctly because the AuthProvider rerenders immediately due to changing its state.
Expected behavior#
What is supposed to be happening
- We are on
/dashboardand the user clicks the logout button - User logs out,
QueryClient.clear()andhistory.replace('/logout')are called AuthProviderrerenders, due to thedataof theuseUserhook now beingundefinedfrom clearing the cache- Since
AuthProviderrerenders, it now passes the correct context down and it's what theuseAuthhook should provide when called. - The page for
/logoutrenders - The
useAuthCheckhook callsuseAuthwhich returnsisAuthenticated: false - Nothing else happens, we stay on
/logoutas logged out users.
How often does this bug happen?#
Every time
Screenshots or Videos#
No videos and screenshots but I have added 2 profiling logs inside the example repo (one with the wrong and one with the correct behaviour) so you can load them in your react profiler and check them
Platform#
- Ubuntu 22.04
- Chrome 126.0.6478.126
Tanstack Query adapter#
react-query
TanStack Query version#
5.51.9
TypeScript version#
5.5.3
Additional context#
No response
TkDodo closed this
TkDodo added labelsworks as designed
TkDodo added labelshas workaround
@TkDodo
Thanks for taking the time! I have since resolved this in a different way, but I did check out the
resetQueriessuggestion now that I read this.That's on purpose, because it would lead to an immediate refetch, putting the component in a hard loading state.
Cool, that's good to know, however
If that's what you want, use queryClient.resetQueries instead.
This showcases the exact same behaviour. If you remove the
enabled: falsefrom theuseUserquery and switchclearwithresetQueries, there is still no immediate rerender in theAuthprovider(you can add a breakpoint to thereturnstatement, and you will see that the breakpoints order shows it does not immediatelly rerender (it should be debugger > debugger > return > debugger, but it's debugger > debugger > debugger > return))
Sign in to join this conversation.
That's on purpose, because it would lead to an immediate refetch, putting the component in a hard loading state. If that's what you want, use
queryClient.resetQueriesinstead.also, I don't understand step 4 in the current behaviour:
if
Logoutrenders, it callsuseAuth, and ifuseAuthcallsuseUserunder the hood, it should read the correct data. But I guess you are copying data fromuseUserinto a context (which usually isn't good) and that's why you get out of sync - because theAuthProvideris higher up the tree.All in all, either use
resetQueriesand prepare for an immediate refetch (which won't happen if you calluseUser({ enabled: false }), but this also is a bit smelly), or remove the Auth Context and just read from the query cache (this is the better fix)