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),…


This content originally appeared on DEV Community and was authored by Anjan Shomodder

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>
    )
}
  • 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 />
        </>
    )
}

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 <>.... </>
}
  • 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 already made a Redux toolkit crash course on my youtube channel. Redux toolkit is a tool to set up and work with redux easily

I have simplified everything for you by building a simple to-do application.

You can demo the application by going to this link . Don't forget to like, share and subscribe to Cules Coding.

project demo

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 .
Stray 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.
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

Email: thatanjan@gmail.com

linkedin: @thatanjan

portfolio: anjan

Github: @thatanjan

Instagram (personal): @thatanjan

Instagram (youtube channel): @thatanjan

twitter: @thatanjan

Blogs you might want to Read:
Eslint, prettier setup with TypeScript and react
What is Client-Side Rendering?
What is Server Side Rendering?
Everything you need to know about tree data structure
13 reasons why you should use Nextjs

Videos might you might want to watch:






This content originally appeared on DEV Community and was authored by Anjan Shomodder


Print Share Comment Cite Upload Translate Updates
APA

Anjan Shomodder | Sciencx (2021-08-25T06:17:08+00:00) 7 reasons why you should use SWR. Retrieved from https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/

MLA
" » 7 reasons why you should use SWR." Anjan Shomodder | Sciencx - Wednesday August 25, 2021, https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/
HARVARD
Anjan Shomodder | Sciencx Wednesday August 25, 2021 » 7 reasons why you should use SWR., viewed ,<https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/>
VANCOUVER
Anjan Shomodder | Sciencx - » 7 reasons why you should use SWR. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/
CHICAGO
" » 7 reasons why you should use SWR." Anjan Shomodder | Sciencx - Accessed . https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/
IEEE
" » 7 reasons why you should use SWR." Anjan Shomodder | Sciencx [Online]. Available: https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/. [Accessed: ]
rf:citation
» 7 reasons why you should use SWR | Anjan Shomodder | Sciencx | https://www.scien.cx/2021/08/25/7-reasons-why-you-should-use-swr/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.