react-queryでSSR/SSG
docs
examples
getStaticPropsの中でQueryClient (tanstack)を呼ぶ
Chrome DevToolsでJavaScriptを無効にして動くことを確認すると良い
queryKeyが完全に一致していないといけない
queryKeyにoptionalなものを含んでいる時に注意
#WIP
例
code:ts
export async function getStaticProps() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery('posts', getPosts)
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
tips
https://react-query.tanstack.com/guides/ssr#tips-tricks-and-caveats
#??
SSGにしたときとそうでないときの、queryやstale部分の差異がわからん
ssgにしたときに、cacheはどうなっているのか
度のタイミングでqueryは古くなったとみなされるのか
ssgしていないときと同じ7日そうでないのか
initialDataの方の短所の説明を見ると、なんか違いがありそうな雰囲気があるが、よくわかっていない
SSGした場合、clientで初期読み込みしたときは
isFetching:false
isLoading:false
になっている
https://react-query.tanstack.com/reference/hydration
2つの方法がある
Prefetch the data yourself and pass it in as initialData
https://react-query.tanstack.com/guides/ssr#using-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
https://react-query.tanstack.com/guides/ssr#using-hydration
clientで若干セットアップしないといけない
全然大した作業ではなかったmrsekut.icon
dehydrationする
serverでprefetchしたときの、updatedAtが継続される?
例えば、staleTimeが10minのとき、どういう挙動になる?
https://github.com/tannerlinsley/react-query/issues/1458#issuecomment-788447705
serializeの箇所でエラーしていた
code:ts
return {
props: {
dehydratedState: JSON.parse(JSON.stringify(dehydrate(queryClient)))
},
revalidate: REVALIDATE_TIME_SHORT
};
こうする以外の回避方法ないんだろうか #??
server側でfetchしたものをcacheに凍結させて、持ち運びできるようにすることをdehydrationと言う
これは、client側でhydrationするための事前準備という感じ
react-queryのqueryをserver→clientに渡せる
react-queryのqueryをlocalStorageなどに永続化できる