userSWR() with Static Export NextJS

userSWR() with Static Export NextJS

The useSWR hook is a very useful tool for state management and cache control in React applications that make requests to external APIs. Developed by the Zeit team, useSWR is one of the most popular packages in the React ecosystem.

useSWR uses data caching in the client's memory technique to avoid unnecessary requests to the server, improving the application's performance. In addition, it also uses an automatic data revalidation strategy at regular intervals, which keeps the application always up-to-date.

Another advantage of useSWR is the ability to use a data transformation function before storing it in the cache. This allows you to process and manipulate data before presenting it to the user interface, simplifying the code and increasing application efficiency.

useSWR is also very easy to use. Just import the package, pass the API URL as a parameter and an optional configuration function that allows you to define options such as the data revalidation time. After that, useSWR returns an object that contains the current state of the request (loading, error, or success) and the data received from the API.

A simple example of using useSWR would be:

'use client'

import useSWR from 'swr'

const fetcher = async (url: string) => {
    const response = await fetch(url)
    return await response.json()
}

export default function Page() {
    const { data, error } = useSWR(
        'https://jsonplaceholder.typicode.com/posts/1',
        fetcher
    )
    if (error) return <p>Failed to load</p>
    if (!data) return <p>Loading...</p>

    return <div>{data.title}</div>
}

In this example, useSWR is used to load data from the API at https://jsonplaceholder.typicode.com/posts/1, and the state of the request is stored in the data and error variables. If there is an error in the request, the component displays the message "Failed to load". If the data has not yet been loaded, the message "Loading..." is displayed. Otherwise, the data is mapped and displayed on the interface.

In summary, useSWR is a very powerful tool for state management and cache control in React applications that make requests to external APIs. With its caching and automatic revalidation strategy, it improves application performance and makes the code more efficient and easy to maintain.

Final Tip - Next Build and useSWR()

For you who will generate NextJS static files using NEXT BUILD, pay attention to the following detail: Place the 'use client' line at the beginning of your component. So the SWR will run on the client side and it will work perfectly.

If you forget, unfortunately the loading of the information with the SWR will not happen.

See you soon, Folks!

PhantoDev