React, React Tutorial

Exploring Client-Side Data Fetching: Leveraging CSR, useEffect, useState, and useSWR

In the world of modern web development, client-side data fetching has become a powerful tool for creating dynamic and interactive user experiences....

Written by Shivangi Rajde · 3 min read >
Exploring Client-Side Data Fetching: Leveraging CSR, useEffect, useState, and useSWR

In the world of modern web development, client-side data fetching has become a powerful tool for creating dynamic and interactive user experiences. This approach shifts the responsibility of fetching and rendering data from the server to the client’s browser. In this article, we’ll delve into the various aspects of client-side data fetching, including its role in client-side rendering (CSR), the useEffect and useState hooks, fetching data with the useSWR library, the benefits of SWR (Stale-While-Revalidate), and a practical code example showcasing the use of useSWR.

The Role of Client-Side Rendering (CSR) in Data Fetching

Client-Side Rendering (CSR) is a rendering technique where web pages are initially loaded with minimal content, often just the basic structure, and then JavaScript is used to fetch additional data from the server and render it on the client side. This approach allows for highly interactive and dynamic web applications, as users can navigate between different parts of the application without waiting for full-page reloads.

Introduction to useEffect and useState Hooks

React, the library that Next.js is built upon offers hooks as a way to manage state and side effects in functional components. The two core hooks relevant to client-side data fetching are useEffect and useState.

  • useEffect: This hook allows you to perform side effects in your functional components, such as fetching data, subscribing to events, or manually altering the DOM. It runs after the render is committed to the screen. To learn more about useEffect hook read this article useEffect: The Effect hook
  • useState: This hook lets you add state management to your functional components. It provides a way to declare variables that can trigger re-renders when their values change. To read more about useState hook read this article useState: Managing State in React functional components.

Fetching Data with the useSWR Library

When it comes to client-side data fetching in Next.js applications, the useSWR library shines as a powerful tool. useSWR combines the benefits of client-side rendering with a smart caching strategy known as Stale-While-Revalidate (SWR). In this section, we’ll delve into the details of using the useSWR library for efficient and responsive data fetching in your web applications.

The useSWR library is a popular choice for client-side data fetching in Next.js applications. It combines the benefits of client-side rendering with the convenience of server-side rendering. SWR stands for Stale-While-Revalidate, a caching strategy that fetches data on the client side, maintains a cached version while updating in the background, and seamlessly transitions to the fresh data.

Understanding Stale-While-Revalidate (SWR)

SWR is a caching strategy that offers a seamless balance between displaying cached data quickly and fetching fresh data in the background. When you use useSWR to fetch data, it first returns the cached data if available (stale), and then it triggers a background fetch to update the data (revalidate). This approach ensures that users see content almost instantly while ensuring data accuracy.

How to Use useSWR for Data Fetching?

The useSWR hook takes two arguments: the key (usually the URL of the API endpoint) and the fetcher function. The fetcher function is responsible for making the actual HTTP request to retrieve the data. Here’s how you can use useSWR:

import React from 'react';
import './style.css';
import useSWR from 'swr';

export default function App() {
  const fetcher = (...args) => fetch(...args).then((res) => res.json());
  const { data, error, isLoading } = useSWR(
    'https://jsonplaceholder.typicode.com/todos/',
    fetcher
  );
  if (error) return <div>failed to load</div>;
  if (isLoading) return <div>loading...</div>;

  return (
    <div>
      
      <div>hello {data.userId}!</div>
      
      <div>
        <h1>Item List</h1>
        <ul>
          {data.map((item) => (
            <li key={item.id}>{item.title}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}

In this example, the useSWR hook fetches a list of items from an API using the fetcher function. It then displays the items in a list, handling loading and error states.

The output the code above would look as shown in the image below:

useSWR Demo
useSWR Demo

Benefits of useSWR

  • Efficient Caching: useSWR caches responses locally, reducing the need for repeated network requests.
  • Reduced Latency: By serving cached data initially, users see content almost immediately while fresh data is fetched in the background.
  • Automatic Revalidation: useSWR automatically triggers data re-fetches at configurable intervals, keeping the data up-to-date.
  • Dependent Fetching: You can use dynamic keys, such as user IDs, with useSWR to fetch data specific to each user.
  • Global State: useSWR allows sharing data across components without resorting to complex state management solutions.
  • Reduced Loading Times: SWR maintains a local cache of data, allowing your application to display content quickly from the cache while fetching fresh data in the background.
  • Improved Responsiveness: The stale-while-revalidate strategy ensures that users see the most recent data without waiting for data fetching to complete, providing a smoother user experience.
  • Network Efficiency: SWR minimizes unnecessary network requests by using cached data whenever possible, reducing the strain on both client and server resources.

Advanced Configuration

useSWR supports advanced configurations through options like revalidateOnFocus, revalidateOnReconnect, and refreshInterval. These options fine-tune how data is fetched and updated based on various scenarios.

Conclusion

Client-side data fetching, enabled by technologies like client-side rendering, useEffect, useState, and libraries like useSWR, empowers developers to create responsive, dynamic, and engaging web applications. By utilizing these tools effectively, developers can provide seamless user experiences while minimizing unnecessary network requests and optimizing performance.

To read more about hooks refer to the links given below:

useState: Managing State in React functional components
useEffect: The Effect hook
useTransition Hook

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *