Client-side Data Fetching with useSWR and fetch

Client-side Data Fetching involves fetching data directly from the client-side, after the initial HTML has been loaded. This approach is suitable for parts of the application that require frequent data updates without changing the entire page structure.

How it Works:

  • In Next.js, you can use libraries like SWR or native JavaScript fetch to fetch data on the client-side.
  • SWR is a popular library that handles data fetching, caching, and revalidating data automatically.
  • When data is fetched on the client-side, it can be dynamically updated without requiring a full page reload.

Use Cases:

  • Real-time updates (e.g., live chat messages, stock prices).
  • Interactive components that fetch data based on user interactions (e.g., search results, infinite scrolling).
  • Parts of the page that don’t need SEO optimization or initial server-side rendering.

Syntax (useSWR):

import useSWR from 'swr';

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

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

if (error) return <div>Error loading data</div>;
if (!data) return <div>Loading...</div>;

return <div>{JSON.stringify(data)}</div>;
}

Example: Below is an example of fetching data using useSWR in NextJS App

JavaScript
// index.js
import { useEffect, useState } from 'react';

export default function Profile() {
    const [data, setData] = useState(null);

    useEffect(() => {
        fetch('/api/user')
            .then((res) => res.json())
            .then((data) => setData(data))
            .catch((error) => console.error('Error fetching data:', error));
    }, []);

    if (!data) return <div>Loading...</div>;

    return <div>{JSON.stringify(data)}</div>;
}

Output:



How to Fetch data faster in Next.js?

NextJS, a popular React framework provides various approaches to fetch data efficiently. Optimizing data fetching can significantly improve the performance and user experience of your NextJS applications.

We will discuss different approaches to Fetch data faster in NextJS:

Table of Content

  • Static Generation using getStaticProps
  • Server-side Rendering using getServerSideProps
  • Client-side Data Fetching with useSWR and fetch

Similar Reads

Steps to Create the NextJS App

Step 1: Create the app using the following command:...

Static Generation using getStaticProps

Static Generation is a Next.js feature that generates HTML pages at build time. This means that the content of these pages is pre-rendered and served as static files, making them extremely fast to load. Static Generation is suitable for pages with content that doesn’t change frequently, such as marketing pages, blogs, or product listings....

Server-side Rendering using getServerSideProps

Server-side Rendering (SSR) in Next.js involves fetching data on each request from the server before rendering the page. This ensures that the content is always up-to-date and can be personalized for each user. SSR is suitable for pages with dynamic content or data that changes frequently....

Client-side Data Fetching with useSWR and fetch

Client-side Data Fetching involves fetching data directly from the client-side, after the initial HTML has been loaded. This approach is suitable for parts of the application that require frequent data updates without changing the entire page structure....