Between SSR, SPA, ISR, RSC, and FCP, the frontend community really loves their three-letter acronyms. Today we're talking about SWR, a term popularized by Vercel's library with the same name. But SWR is more than a library, it's a caching strategy that other frameworks like Laravel are starting to adopt too.
SWR or Stale While Revalidate is a caching strategy to display outdated (stale) data to the user while refreshing (revalidating) it in the background. To illustrate, let's review what an SWR-powered Pokédex would look like.
—
Ash opens his Pokédex for the first time. He has to wait for the PokéAPI to respond before he can browse the list of Pokémon. After waiting a few seconds, he can read about all 1,164 Pokémon. Later that day, Ash opens his Pokédex again. This time, the Pokédex displays the list that was loaded earlier without delay. Simultaneously, the Pokédex does another request to the PokéAPI. If any new Pokémon were discovered since the last time he opened his Pokédex, the list will update.
Without SWR, Ash would need to wait for the list of Pokémon to load every time he opens his Pokédex :snorlax:. With SWR, every subsequent usage of the Pokédex will be instant. This is especially useful for data that doesn't change too often—it's not like we're discovering new Pokémon every day.
—
Vercel's SWR React library provides a useSWR
hook to cache data (mostly API responses) in the current session (or local storage if you want it to cache longer). This ensures a fast user experience while the app fetches fresh data in the background.
With a backend framework like Laravel, you can't real-time-update the UI like you can with React. However, Laravel introduced a flexible cache method configured with two timestamps: an invalidation time and an expiration time. When data is requested from the cache there are three possible outcomes: (1) Invalidation and expiration time are both in the future; just return the cached data. (2) Invalidation time has expired, expiration time in the future; return the cached data and refresh the cache in the background for the next request. (3) Invalidation and expiration time are expired; refresh the cache before returning the request.
Setting a well-configured invalidation and expiration time can ensure a request on a busy page will never stall and provide a fast user experience with data consistently refreshing in the background. Only if a page isn't visited often enough users will be met with longer waits caused by an expired cache.