react-queryでSSR/SSG
queryKeyが完全に一致していないといけない
queryKeyにoptionalなものを含んでいる時に注意
例
code:ts
export async function getStaticProps() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery('posts', getPosts)
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
tips
SSGにしたときとそうでないときの、queryやstale部分の差異がわからん
ssgにしたときに、cacheはどうなっているのか
度のタイミングでqueryは古くなったとみなされるのか
ssgしていないときと同じ7日そうでないのか
initialDataの方の短所の説明を見ると、なんか違いがありそうな雰囲気があるが、よくわかっていない
SSGした場合、clientで初期読み込みしたときは
isFetching:false
isLoading:false
になっている
2つの方法がある
Prefetch the data yourself and pass it in as initialData
簡単に使える
Has some caveats
initialData経由でやるので、custom hookとかにしている場合にグチャる感じがある?mrsekut.icon
別にめちゃくちゃ普通のやりかただな
react-query固有の話は殆どない
デメリット
useQueryをpages/で読んでるなら良いが、下の方や、custom hooks内で読んでる場合は、initialDataをバケツリレーする必要がある
There is no way to know at what time the query was fetched on the server, so dataUpdatedAt and determining if the query needs refetching is based on when the page loaded instead
これに関しては、react-query使っていないときと同じ
ページを読み込んだときが初めてrefetchしたタイミングになる
Prefetch the query on the server, dehydrate the cache and rehydrate it on the client
clientで若干セットアップしないといけない
全然大した作業ではなかったmrsekut.icon
serverでprefetchしたときの、updatedAtが継続される?
例えば、staleTimeが10minのとき、どういう挙動になる?
serializeの箇所でエラーしていた
code:ts
return {
props: {
dehydratedState: JSON.parse(JSON.stringify(dehydrate(queryClient)))
},
revalidate: REVALIDATE_TIME_SHORT
};
server側でfetchしたものをcacheに凍結させて、持ち運びできるようにすることをdehydrationと言う