How to keep next.js client side and server side states in sync?
I'm very confused of what might be the best practise to handle server side and client side state in combination with next.js. As a side note I'm already using tanstack query and jotai for Statemanagement. But I'm open for other options. I read the whole documentation of Tanstack Query and Next.js but I'm still confused to what might be the best approach because the Tanstack Query docs mainly covered server side or client side only but in combination seems still under dev.
Below my code and notes:
2 Replies
genetic-orange•12mo ago
To efficiently manage server-side and client-side state in Next.js using TanStack Query and Jotai, fetch server-side data in
getServerSideProps
and pass it to the client as dehydratedState
to avoid refetching. On the client, use TanStack Query's Hydrate
in _app.js
to load the server-fetched data. Use Jotai for local UI state, and TanStack Query for server-side data management, including caching and syncing with the backend. To prevent frequent refetches, set a staleTime
, and use queryClient.invalidateQueries
to update the data when needed. This ensures smooth state synchronization without unnecessary fetches.deep-jadeOP•12mo ago
Thank you shahid for responding to my question. I already do all of this if you look at my code I've attached in my question. My problem is, I still redundant fetches. And the architecture of my state seems wrong when I read the docs as I have code that is used to validate on the server and on the client.