In this blog article I will explain the stale-while-revalidation pattern.
Stale-while-revalidate is a cache validation strategy. Data, which is fetched from an API, for example, will be cached and consistently updated. The updates get triggered by certain events, like window focusing or mounting. This strategy aims to increase page speed with caching and keep the data up to date.
I implemented this strategy into Portlancer and I was really thrilled by this strategy. The UI renders fewer loading indicators, and the data remains fresh due to the recurring revalidations.
This strategy follows a certain pattern. Before the client requests the data, the client checks whether the data exists in the cache. If it exists, the data will be rendered instantly at the beginning. Nonetheless, the client will fetch fresh data from an API and update the UI and the cache.
SWR is a ReactJS library made by Vercel, which uses the stale-while-revalidate strategy. With the help of SWR, the components get a stream of data, which updates constantly and automatically. With that, the UI will be fast and reactive.
Here is an example of how the SWR library is implemented in code:
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
The first argument of the useSWR hook is a key that will be used to get and store the data in the cache. The second argument is a function that is called by the library, with the key passed as the first argument. The fetcher function must return a promise.
The fetcher can look like this:
function fetcher(url){
return fetch(url).then(response => response.json());
}
If you want to work with the Axios library, you can also use this fetcher for example:
function fetcher(url){
return axios.get(url).then(response => response.data);
}
The stale-while-revalidation strategy saves the data in the local cache and provides the benefit of keeping the balance between immediacy and freshness of the data. The web pages appeal much faster and are more dynamic. But due to the frequent requests made to keep the data fresh, the load of the server increases. With the help of third-party libraries like SWR, it’s possible to leverage this strategy.