Using "swr" Decrease First Contentful Paint and Largest Contentful Paint Time of React Website

March 14, 2021reactswrweb

SWR babbeeehhhhh……

In this case such this website itself, it is built using React+Next.js which utilizes the benefit of using swr instead of the built in function to fetch api.

What is swr?

The name "SWR" is a short for "stale-while-revalidate". It is basically allowing for static pages to fetch api in the background.

How is It Benefit for React?

When deploying a website sometimes we cannot get the fastest bandwidth, so in order to make the website faster we must reduce the amount of data must be downloaded to the browser end. A place to fetch data has been provided by next.js using getInitialPages so that it will wait untill all data finish then render the page, but that is just make the website becoming even longer remembering that the site must load all the data to be finished downloaded then it will render.

By using swr however, the data can be downloaded in the background so the browser just needs to download the page component needed to render the page then in the background swr will fetch the data while the page is rendered.

Application

using server side rendering in next.js

static async getInitialProps({req, res}) {
    const apiResult = await fetcher_function(req);

    return {
        apiResult.data
    }
}

by using above method it will slow the website since it must wait until the data has been fetch before it renders.

Using swr however is much sexier

import useSWR from 'swr'

fetcher_function = (...args) => {
    return fetch(...args).then(res => res.json());
}

componentDidMount() {
    const { data, error } = useSWR('localhost:42069/api/user', fetcher_function)

    const apiResult = data.data;

    if (error) return <div>failed to load</div>
    if (!data) return <div>loading...</div>

    return <div>yeehaa!! {apiResult}</div>
}

The first parameter of useSwr is just the id for the particular data, we can however use other name and fetch using other params instead in the fetcher_function. As the code above we also make sure that while data is fetching we can simply render loading... instead to give a better user feedback.

Other Benefit of Using swr

I am too lazy to explain, go to swr docs instead or watch youtube yourself.