4

While I read SWR react hook documentation and Stale-While-Revalidate methodology, It seems that swr uses cached data just for a short time placeholder to show result to users quickly. (Don't get me wrong I still think swr has many benefits)

I'd like to compare SWR with HTTP static content cache to make things clear.

In terms of HTTP static content cache aka HTTP cache,

  1. Client fetches static content that comes with the Cache-Control or Expires header.
  2. Next time the same content needs to be fetched, As long as the cached file is available and valid based on Cache-Control or Expires. It uses the cached data and doesn't send HTTP request to the server.

However, when it comes to swr useSWR,

  1. it saves HTTP response data to local cache.
  2. Next time the same data needs to be fetched. It uses data from cache(if exists) and sends HTTP requests to server(revalidate) to check if the data has changed.

I know HTTP cache and swr react hook has tons of more features but this is just a brief summary of HTTP cache and swr react hook.

My question is

if swr has to revalidates every time the cached data is used, it doesn't reduce the number of requests other than the concurrent requests of the same API URL from multiple components, right?

If then, is this cache mechanism for showing data quicker to users and may be preventing multiple concurrent requests of the same API URL from multiple components?

I am quite new to swr and please let me know if I misunderstood.

Thanks!

swr docs: https://swr.vercel.app/

HTTP cache on mozilla: https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching

Dennis Martinez
  • 6,344
  • 11
  • 50
  • 67
Shawn
  • 367
  • 4
  • 13
  • 2
    _"swr has to revalidates every time the cached data is used"_ - That's not the case. There's a period of time where SWR will simply use the cached data, and won't send any request. After that period of time has passed and the data is required again, _then_ a new request will be made to revalidate the data. – juliomalves Mar 16 '22 at 23:23

1 Answers1

1

There is an option called dedupingInterval which is set to 2000ms by default. If multiple components request the same cache key/url within this time span no request to revalidate will be send. It can be set globally with SWRConfig context or for each useSWR(key, fetcher, options) hook inside options.

Link: SWR docs

There are more features like using useSWRImmutable(key, fetcher) instead of the useSWR(key, fetcher) to disable revalidation at all.

volkit
  • 1,173
  • 14
  • 21