DEV Community

Cover image for 7 reasons why you should use SWR
Anjan Shomooder
Anjan Shomooder

Posted on

7 reasons why you should use SWR

Why should you use SWR?

SWR is a React Hooks library for remote data fetching.

The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861.
SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

Let's see what problems SWR solves.

  • Auto Revalidation: Suppose, you have opened up your todo application on two tabs. Normally, In one tab if you add a new todo then you won't see the update on the other tab. SWR solves this problem out of the box by auto re-validating. When you change your focus from the tab and then refocus again, swr will make sure the data is valid or up to date. This is done by sending another request to the API.

  • Data Mutation: You can tell swr to re-validate your data with mutation. This is an example from SWR documentation. It shows how to automatically refetch the login info (e.g. inside ) when the user clicks the “Logout” button.

import useSWR, { mutate } from 'swr'

function App() {
    return (
        <div>
            <Profile />
            <button
                onClick={() => {
                    // set the cookie as expired
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'

                    // tell all SWRs with this key to revalidate
                    mutate('/api/user')
                }}
            >
                Logout
            </button>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

By the way, this blog is originally published on cules coding website

Alt Text

I would be glad if you give it a visit.

  • Real-time experience: Suppose you want to create a todo app where you want to add a new todo. But every time you add a new item you have to refresh the page to see the changes. But with SWR mutation you can mutate the request. It simply means, when you add new data, it will automatically fetch another request and will update the UI.

  • Request deduplication: Take a look at this code.

function useUser() {
    return useSWR('/api/user', fetcher)
}

function Avatar() {
    const { data, error } = useUser()

    if (error) return <Error />
    if (!data) return <Spinner />

    return <img src={data.avatar_url} />
}

function App() {
    return (
        <>
            <Avatar />
            <Avatar />
            <Avatar />
            <Avatar />
            <Avatar />
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

Normally it will send the same 3 requests to the API. That is unnecessary. It will take more data and will cause unnecessary rendering. Swr solves this by request deduplication. It will only send one request because they are requested at the same time. The default de-duplicating interval is 2 seconds. But you can change from the config. So it won't cause unnecessary rendering or take more data. It makes our user experience better specifically for mobile devices.

  • Can be used with Both rest and graphql: SWR does not fetch the data. The fetcher function does. And that allows us to use both REST and Graphql API.

  • Built-in caching support: When you first fetch data from an API endpoint it caches the response data. If you send a request to the same API then it will first give you the cached data while fetching the up-to-date data. So that you don't have to show the loading state to the user.

Reusable code: SWR is itself a hook. And you can create a custom hook from hooks. It allows us to write DRY(don't repeat yourself) code. Suppose you want to fetch data from the /users endpoint. So every time you want to fetch the data, you have to pass the fetcher function and options again and again. But if you create a custom hook then you don't have to pass anything again.

function App() {
    const { data, error, isValidating } = useSWR('/users', fetcher)
    return <>.... </>
}

// instead
function useUser() {
    return useSWR('/users', fetcher)
}

function App() {
    const { data, error, isValidating } = useUser()
    return <>.... </>
}
Enter fullscreen mode Exit fullscreen mode
  • Super flexible: You can configure every setting of SWR if you want. You can also set a global configuration. Read more from swr options

And these are the problems that SWR solves. It also has some other features.

  • Built-in Typescript support.
  • Fast, lightweight.
  • Tree shaking vailable.

These are the reasons why I love SWR and you should try it too.

Shameless Plug

I have made a video about how to build a carousel postcard with React, Material-UI, and Swiper.js.
If you are interested you can check the video.

You can also demo the application form here

Screenshot of Insta Carousel

Please like and subscribe to Cules Coding. It motivates me to create more content like this.

If you have any questions, please comment down below.
You can reach out to me on social media as @thatanjan .
Stay safe. Goodbye.

About me

Why do I do what I do?

The Internet has revolutionized our life. I want to make the internet more beautiful and useful.

What do I do?

I ended up being a full-stack software engineer.

What can I do?

I can develop complex full-stack web applications like social media applications or e-commerce sites.

What have I done?

I have developed a social media application called Confession. The goal of this application is to help people overcome their imposter syndrome by sharing our failure stories.
Alt Text

I also love to share my knowledge. So, I run a youtube channel called Cules Coding where I teach people full-stack web development, data structure algorithms, and many more. So, Subscribe to Cules Coding so that you don't miss the cool stuff.

Want to work with me?

I am looking for a team where I can show my ambition and passion and produce great value for them.
Contact me through my email or any social media as @thatanjan . I would be happy to have a touch with you.

Contacts

Blogs you might want to read:

Videos might you might want to watch:







Discussion (0)