How to use the useSWR hook for data caching and revalidation in Next.js



Image not found!!


In Next.js, you can use the useSWR hook from the SWR library (Stale-While-Revalidate) for data caching and revalidation. This hook helps in fetching data, caching it locally (in-memory), and automatically revalidating it in the background when the data is stale. Here's how you can use it:

  1. Install SWR: First, you need to install the SWR library in your Next.js project. You can do this using npm or yarn.

    bash
    npm install swr

    or

    bash
    yarn add swr
  2. Import useSWR: Import the useSWR hook in your Next.js component where you want to fetch and cache data.

    javascript
    import useSWR from 'swr';
  3. Usage: You can use the useSWR hook by providing it with a key (unique identifier for the data) and a function to fetch the data.

    javascript
    const fetcher = (url) => fetch(url).then((res) => res.json()); const MyComponent = () => { const { data, error } = useSWR('/api/data', fetcher); if (error) return <div>Error fetching data</div>; if (!data) return <div>Loading...</div>; return <div>Data: {data}</div>; }; export default MyComponent;
  4. Options: useSWR also accepts an optional third argument for options, where you can specify things like initial data, revalidation intervals, error retry intervals, etc.

    javascript
    const { data, error } = useSWR('/api/data', fetcher, { refreshInterval: 5000, // Revalidate every 5 seconds });
  5. Automatic Revalidation: By default, SWR will automatically revalidate the data in the background when the component is re-rendered after a certain interval (specified by refreshInterval) or when the component is re-mounted.

  6. Manual Revalidation: You can also manually trigger a revalidation by calling the mutate function returned by useSWR.

    javascript
    const { data, error, mutate } = useSWR('/api/data', fetcher); const refreshData = () => { mutate(); }; return ( <div> <button onClick={refreshData}>Refresh Data</button> <div>Data: {data}</div> </div> );
  7. Server-Side Rendering (SSR): If you're using Next.js with server-side rendering, useSWR will automatically disable caching on the server to ensure each request gets fresh data.

That's it! You've now integrated useSWR for data caching and revalidation in your Next.js application.