Reputation: 328
Can I use TanStack Query with the below code example as a replacement of client-side state managers such as Zustand or Redux and therefore, have only one single state manager across the application?
Some benefits / similar features of TanStack Query:
structuralSharing
(which is true
by default) supports comparing nested objects, unlike Zustand's shallow
which only compares the top-level properties of two objectsWhat benefits can client-side state managers have over using TanStack Query locally?
////// Core definitions
const useLocalData = (key:String, initialData:any = null, extraOptions = {}) => {
const { data } = useQuery({
queryKey: [key], initialData, gcTime: Infinity, enabled: false, ...extraOptions
})
return data
}
const setLocalData = (key:String, data:any) =>
queryClient.setQueryData([key], data)
////// Example
// Definition
const useIsChatOpen = () => useLocalData('isChatOpen', false)
const setIsChatOpen = (data:boolean | Function) => setLocalData('isChatOpen', data)
// In the desired component(s)
const isChatOpen = useIsChatOpen()
...
return ...{isChatOpen && <ChatBox/>}
// Anywhere - using specific value
setIsChatOpen(false)
// Anywhere - using setter function
setIsChatOpen(e => !e)
Upvotes: 0
Views: 100
Reputation: 21
Answering your question directly - Yes, you can. But...
So, TanStack Query was designed in mind that it first of all serves utilities for managing server state. So it has many of additional features like caching, revalidating, query keys managing and others. When using it like manager for local state, you need to keep in mind all of that, and not forgot to set all the flags. Also you will end up with some kind of overhead on every state change to reevaluate this and for storing all query object properties like isPending, isError. It is really heavy and useless when you just want to store one bool flag for example.
Traditional client-side state managers simply can serve that task better and with greater DX. They also helps you to organize it in small thunks or stores. Zustand comes with useful tools for shallow comparison for example.
I personally ended up with that combination: using TanStack Query for managing server states and one of light-weight client-side managers for some exclusive pieces of shared client-only states.
Upvotes: 0