T
TanStack•10mo ago
eastern-cyan

Confused about using React Query as a state manager for Nextjs dynamic pages

Hello, I'm a bit confused with how to use the React Query as a state manager. Let's say I have a dynamic route like /list/:slug I first prefetch the query like this.
await queryClient.prefetchQuery({
queryKey: [QueryKeys.equipmentList, listName],
queryFn: () => getListData(listName),
})
await queryClient.prefetchQuery({
queryKey: [QueryKeys.equipmentList, listName],
queryFn: () => getListData(listName),
})
So in order to use the data everywhere on my page, I made this hook
export const useFetchList = (listName?: string | null) =>
useQuery({
queryKey: [QueryKeys.equipmentList, listName],
queryFn: () => getListData(listName as string),
placeholderData: keepPreviousData,
enabled: !!listName,
})
export const useFetchList = (listName?: string | null) =>
useQuery({
queryKey: [QueryKeys.equipmentList, listName],
queryFn: () => getListData(listName as string),
placeholderData: keepPreviousData,
enabled: !!listName,
})
But in order to get the data in other components, I would need to know the value of the current listName because i have to pass it to the hook. So in order to do that, I would need to save it to a global state using something like Zustand right? I would need to initialize the global store with the listName value. Am I understanding this correctly?
3 Replies
complex-teal
complex-teal•10mo ago
you need to make listName available everywhere in your app, yes. A good place is often the url, like /list/foo would have listName: 'foo', while /list/bar would have listName: 'bar' but of course, it depends on what listName is 😅
complex-teal
complex-teal•10mo ago
I'm covering this in my talk here: https://tkdodo.eu/blog/thinking-in-react-query
Thinking in React Query
In this talk, we will learn how a different mindset can help us understand React Query and work with it efficiently.
eastern-cyan
eastern-cyanOP•9mo ago
Thank you!

Did you find this page helpful?