Blog>
Snippets

SWR for Data Fetching and Caching

Implement the use of SWR (Stale While Revalidate) library for efficient data fetching and client-side caching in a Next.js application.
import useSWR from 'swr';

// Function to fetch data from an API endpoint
const fetcher = (...args) => fetch(...args).then(res => res.json());

// Custom hook to use SWR for data fetching and caching
function usePosts() {
    const { data, error } = useSWR('/api/posts', fetcher);

    return {
        posts: data,
        isLoading: !error && !data,
        isError: error
    };
}
Define a custom hook 'usePosts' that uses SWR with a fetcher function to get data from '/api/posts'. It also exposes 'posts', 'isLoading', and 'isError' states.
import React from 'react';
import usePosts from './usePosts';

function PostsComponent() {
    const { posts, isLoading, isError } = usePosts();

    if (isError) return <div>Failed to load</div>;
    if (isLoading) return <div>Loading...</div>;

    return (
        <ul>
            {posts.map(post => (
                <li key={post.id}>{post.title}</li>
            ))}
        </ul>
    );
}
Use the custom hook 'usePosts' inside a functional component to render a list of posts. It handles loading and error states.