DEV Community

Dallington Asingwire
Dallington Asingwire

Posted on • Edited on

How to use SWR in a Next.js app

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); 
  }
Enter fullscreen mode Exit fullscreen mode

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>
    </>
    })
    );
    }
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)