SWR (state-while-revalidate) is a data fetching method built by Vercel. It works by fetching data first, sending a fetch request to revalidate it, then returning the updated data.
SWR is very powerful as it not only allows reusable data fetching but also has built-in caching, pagination, and revalidation on focus. Using SWR, a website displays cached content while it fetches up-to-date content in the background.
How Does SWR Work?
Normally, you'd fetch data using Axios or the fetch method. These methods connect to the data resource, retrieve and return the data then close the connection. However, SWR fetches data differently. It works in three steps:
- Returns stale data from the cache.
- Sends the fetch request to revalidate data.
- Returns up-to-date data.
SWR is not a replacement for the fetch API. Instead, it allows you to render cached content on your site as soon as the user visits and update that content when it becomes stale.
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. After your app renders the stale cached data, SWR will revalidate it and return fresh data that you can use to update the page.
How to Fetch Data in Next.js With SWR
Start using SWR in React by installing it first via a package manager. This command uses npm.
npm install swr\n
In a component file, import the useSWR hook from swr.
import useSWR from "swr"\n
The useSWR hook accepts two arguments:
- A unique identifier for the data. Usually the API URL.
- A fetcher function. This is the function used to retrieve data. It can use fetch, Axios, or other data fetching tools.
The hook returns the data and an error object. Make sure you use this hook in accordance with best practices.
Here is an example showing how to use the useSWR hook.
const fetcher = (...args) => fetch(...args).then(res => res.json());\nconst {data, error} = useSWR("/api/data", fetcher);\n
You can render the data in a component like this:
import useSWR from "swr"\nfunction Home () {\n const fetcher = (...args) => fetch(...args).then(res => res.json());\n const {data, error} = useSWR("/api/data", fetcher);\n if (error) return <div>failed to load</div>\n if (!data) return <div>loading...</div>\n return <div>{data}</div>\n}\n
This is a simple implementation of SWR. The SWR docs go more in-depth so check them out to learn more.
Why Use SWR?
SWR has many advantages over other data-fetching methods.
Caching
With traditional data fetching methods, you have to use a spinner or loading message to improve the user experience when the app is fetching data.
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
Through revalidation, SWR makes the cached data fresh again and the page is re-rendered with up-to-date data. Revalidation is especially important for sites whose content is regularly changing.
The useSWRInfinite hook from SWR lets you implement pagination easily or even create an infinite loading UI.
Scroll Position Recovery
SWR allows a user to return to the scroll position on a page when they come back to it. This contributes to a better user experience.
Dependent Data Fetching
You can fetch data that is dependent on other data. It allows you to use the data returned from one request in another request.
Use SWR to Improve Usability
SWR is a data-fetching tool with an auto-revalidation feature that helps applications render cached content while waiting on up-to-date content. 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.
Author: Matthew Curtis
Last Updated: 1704143282
Views: 2048
Rating: 3.7 / 5 (72 voted)
Reviews: 91% of readers found this page helpful
Name: Matthew Curtis
Birthday: 1914-02-14
Address: 644 Rhodes Centers, South Marissafort, FL 51122
Phone: +4151863459420408
Job: Biologist
Hobby: Arduino, Playing Piano, Cocktail Mixing, Hiking, Cooking, Coin Collecting, Bowling
Introduction: My name is Matthew Curtis, I am a courageous, lively, dear, enterprising, ingenious, unreserved, Colorful person who loves writing and wants to share my knowledge and understanding with you.