While NextJS makes it extremely easy to perform static generation or server-side rendering, it also supports client side fetching. In this post, we will learn how to perform NextJS Client Side Fetching with useSWR hook.

In case you are new to NextJS, you can check out our post on getting started with NextJS.

Also, if you wish to learn more about pre-rendering with NextJS, refer to the below useful posts:

Let us now start with our task of performing client side fetching of data in NextJS.

1 – NextJS Client Side Fetching Normal Way

As you might be aware, NextJS components are nothing but normal React components. In other words, we can write logic in these components in the same way we write in a React component.

In React, we utilize the useEffect hook to call backend services and perform client-side data fetching. The same is possible using NextJS as well.

See below example:

import { useEffect, useState } from "react";

function RandomUser() {
    const [username, setUsername] = useState();
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
         setIsLoading(true);

         fetch('https://randomuser.me/api/?results=1')
         .then(response => response.json())
         .then(data => {
             setUsername(data.results[0].name.first);
             setIsLoading(false)
         });
     }, [])

    if (isLoading) {
        return <p>Loading...</p>
    }

    if (!username) {
        return <p>No data yet</p>
    }

    return <h1>{username}</h1>
}

export default RandomUser;

As you can notice, this is a pretty straightforward component named RandomUser. We have a couple of state variables username and isLoading. We utilize the useState() hook to manage these state variables.

Next, we have the useEffect() hook in which we make a call to an external API that returns a random user object. We use the JavaScript fetch API for the same. Once, we get the response, we call setUsername to update the value of the variable. Also, we set isLoading to false.

Finally, we have some logic to render a rudimentary loading message while the API call is in progress. Once the username is available, we show that on the screen.

2 – NextJS Client Side Fetching with useSWR

Now, we can see how to perform the same client side data fetching in NextJS with useSWR() hook.

Basically, useSWR() is a React hook for data fetching. This hook has been created by the team that has developed NextJS. However, it is possible to use this hook even without NextJS.

The term SWR stands for stale-while-revalidate. Basically, it is a cache invalidation strategy that first returns the data from the cache, then sends the fetch request for validation. After validation, we get the up-to date data.

The useSWR() hook provides a fast and lightweight approach of data fetching. It also provides a built-in cache and request de-duplication feature. To utilize the useSWR() hook with NextJS, we need to install the below package.

$ npm install swr

Once we have the package installed, we can tweak our component as below:

import { useEffect, useState } from "react";
import useSWR from "swr";

function RandomUser() {
    const [username, setUsername] = useState();

    const {data, error} = useSWR('https://randomuser.me/api/?results=1', 
        (url) => fetch(url).then(res => res.json()))
    useEffect(() => {
        if (data) {
            setUsername(data.results[0].name.first);
        }
    }, [data])

    if (!data) {
        return <p>Loading...</p>
    }

    if (error || !username) {
        return <p>No data yet</p>
    }

    return <h1>{username}</h1>
}

export default RandomUser;

As you can see, we first import useSWR from the swr package. Next, we call the useSWR hook from within our component code.

Basically, the useSWR() hook takes the URL and a callback function as input. Within the callback function, we call the fetch API and then we again call useEffect() hook to set the received data to the username variable.

Do note that here useEffect has a dependency data. Only when data is available after the API call, the hook will execute.

Lastly, we just render the username in the component.

Conclusion

The NextJS useSWR hook for client side data fetching may not look strikingly different as compared to the normal approach. However, it provides caching and performance benefits. Also, it has good support for other utilities such as pagination and validation.

This makes it a suitable candidate for consideration when we need to perform client side fetching in NextJS.

Want to use NextJS with Firebase? Check out this post on NextJS firebase integration for static and server-side rendering.

If you have any queries or comments about this post, please feel free to mention them in the comments section below.

Categories: NextJS

0 Comments

Leave a Reply

Avatar placeholder

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