Understanding Tanstack Query as state

Hey there! I am hoping someone can help me understand the concept of using Tanstack Query (React Query) as a state manager? I have been reading articles and even playing around with some code myself on how lots of people love using TQ as a state management tool. The idea that your state lives on server-side and you app simply reads from query/cache. This of course seems really cool especially for say data tables etc. But I am struggling to understand the concept of possibly using that for something that is maybe more traditionally aa client-side state but moving it to server side? Let's say you have user's preferences stored in the database. You could store things like, what colour theme they're using and maybe some other things. You use TQ to fetch this data from the server so on load we know what theme the user has chosen, but now we want them to be able to change their theme choice! Traditionally we'd just use a useState or a Zustand store and our Theme Provider can base what it is showing off that state. Is the idea with TQ that we would trigger a mutation (edit the user's preferences) and then invalidate the TQ query on the user's theme provider so that the theme then updates? So the state is sort of doing a round-trip?: User changes theme -> mutation to the database -> invalidate database theme query -> UI updates theme Is this the recommended pattern? In my head this works perfectly fine but just feels a bit clunky or slow? Other options being: User loads page -> TQ pulls state from database -> state is loaded into something like Zustand -> User changes theme (through zustand) -> UI updates immedietly -> mutation goes to the database Perhaps there's some guides/teachings on this issue? I'm struggling to find much and usually articles only focus on using localStorage which is not what I want!
2 Replies
msvc
msvc5mo ago
tanstack query is for async state, not general UI state. but yes, what you are thinking is correct the secret is that mutations have optimistic updates (via the .variables property) so that in reality your update flow looks more like this: fetch state -> mutate state -> optimistic update from mutation state -> invalidate state once mutation finishes -> fetch state, override optimistic update
Filipi
Filipi5mo ago
Here's the docs for the optimistic update. You can either do it via the variables property or via the query cache https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates
Optimistic Updates | TanStack Query React Docs
React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the onMutate option to update your cache directly, or leverage the returned variables...

Did you find this page helpful?