Server-side data fetching
As we have seen, data fetching does not work out of the box on the server side. There are two approaches for server-side data fetching with React Query:
- Initial data approach: Use the
initialData
option in theuseQuery
hook to pass prefetched data in. This approach is enough for fetching a list of posts but would be tricky for fetching deeply nested data, such as the usernames of each author. - Hydration approach: This allows us to prefetch any requests and store the result by their query key and prefetch any request on the server side, even if it is deeply nested within the app, without having to pass the prefetched data down using props or a context.
We are first going to use the initialData
option to fetch the list of blog posts, and then extend our solution to the hydration approach so that we can get a feeling for how both approaches work and what their pros and cons are.
Using initial data
React Router allows us to define loaders...