Using setQueryData instead of initialData for populating query cache with server-side rendering (SSR) #2844
-
TL;DR The docs are recommending setting Why not use I have a common use case: Creating an "Incremental static regeneration" page with Next.js that also fetches data from the database. Now, I can give that data down to the page via props as well. Usually, when this page renders, it also executes a In the docs, there are two ways described on how to do this with Next.js. The downsides are already described in the docs, mainly that you have to move the data via props, maybe even multiple levels deep in your component tree. Using export const getStaticProps: GetStaticProps<MyPageProps, Params> =
async () => {
const myData = (await fetchSomeData()).result;
return {
props: {
myData : myData ?? null,
},
revalidate: revalidateInSeconds,
};
};
export default function _MyPage(props: MyPageProps): JSX.Element {
if (props.myData) {
queryClient.setQueryData<QueryDataType>([queryKey], props.myData);
}
// SomePage will use "useQuery" inside
return <SomePage myData={props.myData} />;
} This works really well! The statically created page also contains the fetched data that way. Even if I disable the So my question is: What are the disadvantages of this method, respectively why is it not recommended in the docs? Bonus question: There's one thing I don't understand though: The The data with a export default function IndexPage({ myData }) {
// A)
if (true) {
queryClient.setQueryData([queryKeys.withServerData], myData);
}
return (
<MyDataComponent
// B)
shouldFetchOnClient={true}
dataFromServer={myData}
queryKey={queryKeys.withServerData}
/>
);
} If you disable If both A) and B) are active (= Is that because I use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
That is not what the
I still think this is the easiest way to prefetch multiple queries on the server. Sure you could do the same thing with setQueryData, but it's pretty manual, and actually the same thing that the hydration is doing: Putting data into the cache on the frontend. Except that it already had the correct structure.
At the moment you call Also, you can't really call |
Beta Was this translation helpful? Give feedback.
That is not what the
hydration
method is doing though :) By using it, you create a "temporary" cache that has the correct structure that your queries will have. By dehydrating it, you'e sending the correct structure to the client. The cache is created inside getStaticProps every time, so it doesn't really cache anything:I still think this is the easiest way to prefet…