-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Description
This is in a sense a continuation of the now closed #70
First of all, thanks for your hard work on this library, it's great! I'm currently designing a new somewhat complex data fetching solution at work and I would like to build it on top of react-query, but there is some functionality around SSR that I would like to discuss.
I think the call to not cache data at all in #70 was the right one given the circumstances, for security reasons there can not be a cache by default on the server since it might leak user data cross-requests. However, this has some cumbersome consequences:
- Using
queryCache.prefetchQuery
ahead of the server rendering (like in Next.jsgetInitialProps
) wont automatically prime the cache - Calling
useQuery
withinitialData
in one place wont prime the cache for use in a second place, so reading the same data from the cache in multiple places becomes impossible
A big point of react-query is to be the global cache for data. Since this is not true on the server, a lot of nice patterns falls apart, and the only way to fix that is to implement your own cache on the server that wraps react-query, for example using a custom useQueryWithSSRCache
that passes some initialData
every time it is used. This seems a bit backwards since it's re-implementing a somewhat big part of react-query.
My suggestion is to make using a cache on the server opt-in and design it around creating a new cache per request, that you place on a context provider. If a cache is available on the context, use that instead of the global one.
The other part of the puzzle is to make that cache serialisable (and you probably want to destroy the entire cache when you do so), so you can send it to the client and hydrate it there. On the client you could either hydrate the global cache before rendering, or create a cache and place on a context like on the server (but then you can't import queryCache
like normal).
This is also something that will very likely be needed to support Suspense server rendering on the server in the future, if you don't have a cache per request, what do you read from to see if you need to Suspend or not? I'm not sure if this is something you are interested in, or if you deem it out of scope for the library? From the Readme:
Query caches are not written to memory during SSR. This is outside of the scope of React Query and easily leads to out-of-sync data when used with frameworks like Next.js or other SSR strategies.
(Btw, I'm curious about what you mean by out of sync here?)
I'd love to get your input on this! This is a complex area so even if this became somewhat long, there is still a lot of nuance here of course, I'm very open to discussing it further and might very well be interested in contributing to something like this as well.