Can I combo Tanstack query and Server component on Nextjs?
I was using Tanstack query for server state management with Nextjs, But I was concerned that almost all my components are getting 'use client ' so Is therr any design pattern or way to benefit both world ?
20 Replies
I do it, we prefetch the queries on the server and the hydrate them on the client to achive pooling/realtime data
We also try to put "use client" only on the "leaves" components
@Gary, el Pingüino Artefacto Do you have example repo please?
@Gary, el Pingüino Artefacto Is initialData good approach?
fetch initially on server component and pass it to client component, then inside the client component pass the initialData to queryClient ?
in which the queryClient is a custom hook for data fetching
no
i prefer this
initialData makes prop drilling
@Gary, el Pingüino Artefacto Okay, so I have to use the hydration boundary on every page ?
yes
It's kinda annoying but I prefer it than passing props
Does the prefetch streaming approach send html to browser or the data it self?
i haven't try it, i think it just send the promises and resolve it on the client
so only the data is sent
oh but If I used the initial data approach, it will send the html, right?
@Gary, el Pingüino Artefacto Here is what I know so far:
- if I used the server component to fetch data it will send html so the network tab ( browser ) doesn't show the data structure, it will be RSC payload
- But when I used the tanstack query to fetch data, on the network tab, the payload is showing the data structure on the response
Am I correct ?
the prefetch/hydrate and the initial data di exactly the same thing
Oh so the payload is RSC like
yes
great, thanks
you will still need the "use client" directive when using react query
But If I don't use the prefetch + hydrate, it will not be RSC payload, right ?
yeah, I know
it will still be ssr if thats what you are asking
Hmm, I don't understand
This is what my provider looks like
I think I should have used HydartionBoundary to benefit this approach, in which I'm not using currently
this is mine
i called makeQueryClient on the server and use a HydrationBoundary with the prefetch
thats enought to get ssr working
@Gary, el Pingüino Artefacto Then, I use this on pages ( HydrationBoundary )
BTW, what's the core difference ( your implementation from mine )