Blog>
Snippets

Using the SWR Hook for Data Fetching

Provide an example of how to use the SWR hook for efficient data fetching, caching, and revalidation in a Next.js component.
import useSWR from 'swr';

// Define a fetcher function that uses the native fetch API
const fetcher = (...args) => fetch(...args).then(res => res.json());

function UserProfile({ userId }) {
  // Use the SWR hook with the fetcher function and a unique key
  const { data, error } = useSWR(`/api/user/${userId}`, fetcher);

  if (error) return <div>Failed to load user</div>;
  if (!data) return <div>Loading...</div>;

  // data is the user fetched, render the UI with data
  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </div>
  );
}

export default UserProfile;
This code is a simple Next.js component that uses the SWR hook for data fetching. The 'useSWR' function is imported from the 'swr' library. A fetcher function that uses the native fetch API to get JSON data is defined. Within the 'UserProfile' component, the 'useSWR' hook is used with a unique key based on the 'userId' prop to fetch user data from an API endpoint. The 'data' and 'error' properties returned from 'useSWR' are used to conditionally render the user data or show loading and error messages.