Blog>
Snippets

Fetching Data on the Client Side with SWR

Show how to use SWR for client-side data fetching with caching, revalidation, and error handling in a Next.js app.
import useSWR from 'swr';
Import the useSWR hook from the swr library.
const fetcher = (...args) => fetch(...args).then(res => res.json());
Define a fetcher function that uses the native fetch API to retrieve data and then parse the response as JSON.
function UserProfile({ userId }) {
  const { data, error } = useSWR(`/api/user/${userId}`, fetcher);

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

  return <div>Hello, {data.name}!</div>;
}
Create a UserProfile component that fetches user data using the useSWR hook with a dynamic API endpoint based on the userId prop. It handles states for loading and error, returning appropriate UI feedback.
<style>
  .error { color: red; }
  .loading { color: gray; }
</style>
CSS styles for the error and loading states.
<div id='user-profile'>
  <UserProfile userId='123' />
</div>
HTML markup with a div element where the UserProfile component is rendered, passing a mock userId prop.