Next JS Data Fetching Using useEffect and SWR


Client-side data fetching in Next.js can be accomplished using several methods, with the most common being the useEffect hook from React and the SWR library. Both approaches allow you to fetch data on the client side after the initial server-side render, enabling you to create dynamic and interactive applications.

1. Client-Side Data Fetching with useEffect

The useEffect hook is a built-in React hook that allows you to perform side effects in functional components, including data fetching. Here’s how to use it for client-side data fetching:

Example

import { useEffect, useState } from 'react'; const UserProfile = ({ userId }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchUser = async () => { try { const response = await fetch(`https://api.example.com/users/${userId}`); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); setUser(data); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchUser(); }, [userId]); // Fetch data when userId changes if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error}</p>; return ( <div> <h1>{user.name}</h1> <p>Email: {user.email}</p> </div> ); }; export default UserProfile;

Explanation of the Code

  1. State Management:

    • user: Holds the fetched user data.
    • loading: Indicates if the data is still being fetched.
    • error: Stores any error messages during the fetch.
  2. useEffect Hook:

    • The useEffect hook is called after the component mounts.
    • An asynchronous function fetchUser is defined to fetch the user data.
    • The fetch API is used to retrieve data, and the response is handled.
    • The state is updated with the fetched user data, loading status, or any errors encountered.
  3. Dependency Array:

    • The hook has a dependency on userId, meaning it will re-run whenever userId changes.
  4. Conditional Rendering:

    • While loading, a loading message is displayed.
    • If there’s an error, the error message is shown.
    • Once the data is successfully fetched, the user details are rendered.

2. Client-Side Data Fetching with SWR

SWR (stale-while-revalidate) is a React Hooks library created by Vercel (the creators of Next.js) for data fetching. It provides a powerful, easy-to-use API that simplifies the process of fetching data, caching it, and revalidating it.

Example

import useSWR from 'swr'; const fetcher = (url) => fetch(url).then((res) => res.json()); const UserProfile = ({ userId }) => { const { data: user, error } = useSWR(`https://api.example.com/users/${userId}`, fetcher); if (!user && !error) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <h1>{user.name}</h1> <p>Email: {user.email}</p> </div> ); }; export default UserProfile;

Explanation of the Code

  1. SWR Hook:

    • The useSWR hook is used to fetch data. It takes two arguments: the URL to fetch and a function to fetch the data (fetcher in this case).
  2. Fetcher Function:

    • The fetcher function uses the fetch API to get the data from the provided URL and returns the parsed JSON.
  3. Data and Error Handling:

    • The data returned by useSWR is renamed to user for clarity.
    • If no data and no error are available, a loading message is displayed.
    • If an error occurs, the error message is shown.
  4. Automatic Revalidation:

    • SWR automatically handles caching, revalidation, and stale data, making it very efficient for client-side data fetching.

Comparison of useEffect and SWR

  • Complexity:

    • Using useEffect requires more boilerplate code to manage loading states, errors, and data.
    • SWR simplifies this process with a cleaner API and built-in caching and revalidation features.
  • Automatic Features:

    • SWR offers automatic revalidation and focus tracking (refetching data when the user returns to the page), while with useEffect, you need to implement this manually.
  • Error Handling:

    • SWR provides a straightforward way to handle errors directly within the hook.

Summary

Client-side data fetching can be done effectively using either the useEffect hook or the SWR library in Next.js. While useEffect offers flexibility and control, SWR simplifies data fetching with built-in caching and automatic revalidation features, making it a popular choice for modern React applications. Depending on your project’s needs, you can choose the method that best fits your use case for fetching and displaying dynamic data.