SWR is one of the OSS of Vercel, the company makes Next.js.
SWR is a React Hooks library for remote data fetching.
The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861.
SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
SWR does a polling fetch by default
SWR, by default, verifies data once every 5,000ms and detects differences so that changes can be reflected in the frontend.
Firestore is charged based on the number of reads and writes, so too much polling and fetching will increase the cost.
If you use SWR, please read the documentation carefully before implementing it.
If you don't need polling fetch, stop the revalidation and fire the revalidate event at the timing you want to re-fetch.
const { data: posts, revalidate } = useSWR('firestore/posts', fetchPosts, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
});
Or, try to get a wide range in the interval between revalidations.
const { data: posts } = useSWR('firestore/posts', fetchPosts, {
focusThrottleInterval: <number> // 再検証したい間隔
});