SWR (state-while-revalidate) is a data fetching method built by Vercel.
Using SWR, a website displays cached content while it fetches up-to-date content in the background.
How Does SWR Work?
Normally, you’dfetch data using Axios or the fetch method.
These methods connect to the data resource, retrieve and return the data then kill the connection.
However, SWR fetches data differently.
It works in three steps:
SWR is not a replacement for the fetch API.
So how does SWR know when the cache is invalid?
Through a cache-control header response.
The response has two states: fresh and stale.
A fresh state means the cache can be reused while a stale state means it’s invalid.
You specify the time the response remains valid in the max-age directive.
SWR considers any cached response older than max-age invalid.
This command uses npm.
In a component file, import the useSWR hook from swr.
The useSWR hook accepts two arguments:
The hook returns the data and an error object.
double-check youuse this hook in accordance with best practices.
Here is an example showing how to use the useSWR hook.
TheSWR docsgo more in-depth so check them out to learn more.
Why Use SWR?
SWR has many advantages over other data-fetching methods.
SWR allows you to display stale data to the user, while you revalidate it.
This means the user does not have to wait for the fetcher to return data.
Revalidation is especially important for sites whose content is regularly changing.
Pagination
TheuseSWRInfinite hookfrom SWR lets you implement pagination easily or even create an infinite loading UI.
This contributes to a better user experience.
Dependent Data Fetching
you could fetch data that is dependent on other data.
It allows you to use the data returned from one request in another request.
Users can engage with content right away instead of waiting on the server to return data.
SWR also helps you create pagination, infinite loading, scroll position recovery, and other complex features.
If you are fetching data that needs regular updates, you should definitely consider using it.