How to use the useSWR hook for data fetching in Next.js



Image not found!!

useSWR is a React hook for data fetching in Next.js applications. It is part of the SWR library (standing for "stale-while-revalidate"). SWR is a strategy to first return the data from the cache (stale), then send the fetch request in the background (revalidate), and finally come with the up-to-date data. This helps to provide a smooth user experience.

Here's a simple example of how you can use useSWR in a Next.js application:

  1. First, you need to install the swr package:

    bash
    npm install swr # or yarn add swr
  2. Then, you can use useSWR in your Next.js component:

    jsx
    // Import necessary dependencies import useSWR from 'swr'; // Define a function to fetch data const fetchData = async (url) => { const response = await fetch(url); const data = await response.json(); return data; }; // Define your functional component const MyComponent = () => { // Use useSWR hook with the fetch function and the data URL const { data, error } = useSWR('/api/data', fetchData); // Check if data is loading if (!data) return <p>Loading...</p>; // Check if there is an error if (error) return <p>Error loading data</p>; // Render your component with the fetched data return ( <div> <h1>Data:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }; export default MyComponent;

In this example:

  • useSWR('/api/data', fetchData) is used to fetch data from the /api/data endpoint using the fetchData function.
  • The data variable holds the fetched data, and the error variable holds any potential error that might occur during the fetching process.
  • The component checks if the data is still loading or if there is an error before rendering the content.

Note: Ensure that the fetchData function returns the data in the expected format. Additionally, you may customize the useSWR hook by providing options such as revalidateOnFocus, revalidateOnReconnect, etc. Refer to the SWR documentation for more details on customization options.