How to use SWR in a Next.js app
SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally come with the up-to-date data.
Dallington Asingwire
SWR stands for stale-while-revalidate . It's a lightweight library that allows fetching, caching, or refetching data in realtime with React Hooks.
import useSWR from "swr";
const fetcher = (url) => fetch(url)
.then((res) => res.json())
.then(json => {
return json
});
const useSwrFetcher = url => {
return useSWR(url, fetcher);
}
To use SWR, you first install it in your project using npm or yarn e.g npm i swr or yarn add swr.
In the above code snippet, a functional component fetcher takes api url as a parameter and then returns a json response from the api.
Then a reusable functional component useSwrFetcher (you can name it any) calls useSWR hook and passes the api url and fetcher(you can give it any name) to return data from the api.
Example below demonstrates the use of reusable component useSwrFetcher
const API_URL = 'typeyourapihere...';
export const Users = () => {
const {data: users, error} =
useSwrFetcher(API_URL+"/users");
return (
users.map((user, i) => {
return <>
<span>Name: {user.name}</span>
<span>Age: {user.age}</span>
</>
})
);
}
The function component Users calls reusable component useSwrFetcher to get users from the API and then uses map function to display the data(name and age) for the fetched users. I hope this article draws a picture to you on how to use swr in a next.js app. Thank you for reading through.
Upvote
Dallington Asingwire
Software Engineer. I do develop in Javascript( React, Next.js and React Native), Java and PHP

Related Articles