This video is available to students only

Stale While Revalidate

Here we'll learn how to prefetch data based on the route

This lesson explores the concept of stale while revalidate and how it can be implemented in a data fetching library. Stale while revalidate refers to the practice of returning cached data immediately while fetching newer data in the background.

This strategy can significantly improve the perceived performance of an application, particularly those that require up-to-date data like stock market apps or social media feeds. While the example app in this lesson may not require real-time data, stale while revalidate will be implemented to demonstrate its functionality.

Understanding SWR#

The term stale while revalidate originates from the HTTP cache control header. It means that if you already have cached data and want to revalidate or fetch new data, you can immediately return the cached data while fetching the newer data in the background. Once the new data is fetched, the previously cached data is considered stale.

Explanation of how Stale while revalidate works

Implementing this strategy can enhance the performance of applications that rely on up-to-date information.

Implementing SWR#

To implement stale while revalidate in a data fetching library, a few steps need to be followed. First, it's necessary to check if the option for refetching on component mount is enabled. Additionally, it's important to ensure that the data's status is not currently loading or idle, as we are only interested in refetching data that has already been fetched. Furthermore, to prevent an infinite refetch loop, it's necessary to check if the data is stale, meaning it is older than a certain time threshold.

How it will work in our app

First let's add an option called refetchOnMount and set it to true in our home component.

This option doesn't yet exist but we're going to implement it in our data loader file.

In our useData hook, above the return statement, let's add an if statement to first check if the refetchOnMount option is set to true and also if the data status is set to success.

The refetching option doesn't yet exist in the prefetchData function but the reason it exists is to change the state of the data to refetching in case the user wants to show a refetching specific loader or something.

Don't forget to add options as a third argument in the useData hook.

Let's implement this in the prefetchData function. We'll first pass the options argument into the function.

This lesson preview is part of the React Data Fetching: Beyond the Basics course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to React Data Fetching: Beyond the Basics, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course React Data Fetching: Beyond the Basics