codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

15 / 73 topics
10Data Fetching Methods (getStaticProps, getServerSideProps)11Static Site Generation (SSG)12Server-Side Rendering (SSR)13Incremental Static Regeneration (ISR)14Client-Side Data Fetching15SWR Library for Client-Side Data Fetching
Tutorials/Next.js/SWR Library for Client-Side Data Fetching
▲Next.js

SWR Library for Client-Side Data Fetching

Updated 2026-04-20
3 min read

SWR Library for Client-Side Data Fetching

In this section, we will explore the use of the SWR (Stale While Revalidate) library in a Next.js application. SWR is a highly efficient and lightweight data fetching library that simplifies client-side data fetching and caching. It provides features like automatic revalidation, background updates, and built-in error handling, making it an excellent choice for modern web applications.

Introduction to SWR

SWR stands for "Stale While Revalidate," which means that the application will first display stale data (if available) and then fetch fresh data in the background. This approach enhances performance by reducing the number of requests made to the server while ensuring that users always see up-to-date information.

Setting Up SWR in a Next.js Project

To use SWR in your Next.js project, you need to install it first. You can do this using npm or yarn:

npm install swr

or

yarn add swr

Once installed, you can import and use the useSWR hook provided by SWR in your components.

Basic Usage of SWR

The useSWR hook is used to fetch data from a specified URL. It returns an object containing the data, error, and loading status.

Example: Fetching User Data

Let's create a simple example where we fetch user data from an API using SWR.

// pages/user.js
import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function User() {
  const { data, error } = useSWR('/api/user', fetcher);

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

  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </div>
  );
}

Explanation

  • Fetcher Function: The fetcher function is responsible for making the HTTP request. It takes a URL as an argument and returns the parsed JSON response.
  • useSWR Hook: The useSWR hook is called with the API endpoint (/api/user) and the fetcher function. It returns an object containing:
    • data: The fetched data.
    • error: Any error that occurred during the fetch.
    • isValidating: A boolean indicating whether the data is being revalidated.

Advanced Usage of SWR

SWR offers several advanced features that can be leveraged to enhance your application's performance and functionality.

Revalidation Strategies

SWR supports different revalidation strategies, such as:

  • Revalidate on Focus: Automatically revalidate data when the window regains focus.
  • Revalidate on Interval: Periodically revalidate data at a specified interval.

Example: Revalidate on Focus

// pages/user.js
import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function User() {
  const { data, error } = useSWR('/api/user', fetcher, {
    revalidateOnFocus: true,
  });

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

  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </div>
  );
}

Error Handling

SWR provides built-in error handling, which can be customized to suit your application's needs.

Example: Custom Error Handling

// pages/user.js
import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function User() {
  const { data, error } = useSWR('/api/user', fetcher);

  if (error) return <div>Failed to load: {error.message}</div>;
  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </div>
  );
}

Data Mutation

SWR provides a mutate function that allows you to update the cached data programmatically.

Example: Updating User Data

// pages/user.js
import useSWR, { mutate } from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function User() {
  const { data, error } = useSWR('/api/user', fetcher);

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

  const updateUser = async () => {
    const response = await fetch('/api/user', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'New Name' }),
    });

    if (response.ok) {
      mutate('/api/user'); // Revalidate the data
    }
  };

  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
      <button onClick={updateUser}>Update Name</button>
    </div>
  );
}

SWR Configuration

You can configure SWR globally using the SWRConfig component, which allows you to set default options for all SWR hooks.

Example: Global Configuration

// pages/_app.js
import { SWRConfig } from 'swr';
import '../styles/globals.css';

const fetcher = (url) => fetch(url).then((res) => res.json());

function MyApp({ Component, pageProps }) {
  return (
    <SWRConfig value={{ refreshInterval: 3000 }}>
      <Component {...pageProps} />
    </SWRConfig>
  );
}

export default MyApp;

Best Practices

  1. Use fetcher Function: Always use a separate fetcher function to handle HTTP requests, making your code more modular and reusable.
  2. Error Handling: Implement robust error handling to provide feedback to users in case of data fetching failures.
  3. Data Mutation: Use the mutate function to update cached data after performing mutations like updates or deletes.
  4. Global Configuration: Use SWRConfig for global settings to avoid repeating options across multiple SWR hooks.

Conclusion

The SWR library is a powerful tool for client-side data fetching in Next.js applications. Its features like automatic revalidation, background updates, and built-in error handling make it an excellent choice for modern web development. By following the best practices outlined in this guide, you can effectively integrate SWR into your Next.js projects to enhance performance and user experience.

Feel free to explore more advanced features of SWR in the official documentation: SWR Documentation.


PreviousClient-Side Data FetchingNext CSS Modules

Recommended Gear

Client-Side Data FetchingCSS Modules