Catch, Optimize Client-Side Data Fetching in Next.js Using SWR
Tags: webdev, javascript, beginners, programming
Published: 2024-06-27 01:49:23

### How to Optimize, Memorise Client-Side Data Fetching in Next.js Using SWR

In modern web applications, efficient data fetching is crucial for providing a smooth and responsive user experience. Next.js, a popular React framework, offers several ways to fetch data. One effective method is using the SWR (stale-while-revalidate) library, which provides a powerful and flexible approach to data fetching and caching. In this article, we'll explore how to use SWR for client-side data fetching in a Next.js application, and we'll compare it with traditional React hooks for data fetching.


---

{% youtube https://www.youtube.com/watch?v=OjAwwGV38Ms %}
----

{% github https://github.com/SH20RAJ/nextbuild %}

#### Why Use SWR?

SWR is a React Hooks library for data fetching developed by Vercel, the team behind Next.js. SWR stands for stale-while-revalidate, a cache invalidation strategy. It provides several benefits:

1. **Optimized Performance**: SWR caches the data and revalidates it in the background, ensuring the user always has the most up-to-date information without waiting.
2. **Automatic Revalidation**: Data is automatically revalidated at intervals, keeping it fresh.
3. **Focus on Declarative Data Fetching**: SWR abstracts away much of the boilerplate associated with data fetching.

#### Setting Up the Next.js Project

First, create a new Next.js project if you haven't already:

```bash
npx create-next-app@latest swr-example
cd swr-example
```

Install the SWR library:

```bash
npm install swr
```

#### Basic Routing Setup

Let's set up basic routing with a `Home` page and two additional pages to demonstrate data fetching using SWR and traditional React hooks.

**`app/page.js`**

```javascript
import Link from "next/link";

export default function Home() {
  return (
    <>
      <div>
        <Link href="/new">New</Link>
        <br />
        <Link href="/new2">New2</Link>
      </div>
    </>
  );
}
```

#### Fetching Data with SWR

Create a new page that uses the SWR library to fetch data from an API.

**`app/new/page.js`**

```javascript
'use client';
import Link from 'next/link';
import useSWR from 'swr';

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

export default function Page() {
  const { data, error } = useSWR('https://jsonplaceholder.typicode.com/posts/1', fetcher);

  if (error) return 'Failed to load';
  if (!data) return 'Loading...';

  return (
    <>
      <Link href="/">Main</Link>
      <br />
      <div>Data Title: {data.title}</div>
    </>
  );
}
```

#### Fetching Data with React Hooks

Create another page that fetches the same data using traditional React hooks.

**`app/new2/page.js`**

```javascript
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';

export default function Page() {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((json) => {
        setData(json);
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setLoading(false);
      });
  }, []);

  if (loading) return 'Loading...';
  if (error) return `Error: ${error.message}`;

  return (
    <>
      <Link href="/">Main</Link>
      <br />
      <div>Data Title: {data.title}</div>
    </>
  );
}
```

### Comparison: SWR vs. React Hooks

**SWR:**

- **Pros:**
  - Automatic caching and revalidation.
  - Easier to manage and less boilerplate code.
  - Better performance due to background revalidation.
- **Cons:**
  - Requires additional dependency.

**React Hooks:**

- **Pros:**
  - Native to React, no additional dependencies required.
  - More control over the data fetching process.
- **Cons:**
  - More boilerplate code for handling loading and error states.
  - No built-in caching or revalidation.

### Conclusion

Using SWR for data fetching in a Next.js application offers several advantages, including automatic caching, revalidation, and reduced boilerplate code. While traditional React hooks provide more control, they require more effort to handle common scenarios like caching and error handling. Depending on your application's needs, SWR can be a powerful tool to enhance performance and user experience.

For more detailed information, you can also refer to the [SWR documentation](https://swr.vercel.app/) and the Next.js [official documentation](https://nextjs.org/docs).

### Troubleshooting

{% github https://github.com/SH20RAJ/nextjs-loading-problem %}

{% post https://dev.to/sh20raj/nextjs-loading-problem-refetching-api-data-on-revisit-64822-3i10 %}

> https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side

If you encounter issues such as loading problems, check out the [Next.js loading problem issue](https://github.com/SH20RAJ/nextjs-loading-problem) on GitHub for community-driven solutions and discussions.