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.

7 reasons why you should 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.

Why should you use SWR?

Let's see what problems SWR solves.

  • Auto Revalidation: Suppose, you have opened up you 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 really 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 done through sending another request to the API.

  • Data Mutation: You can tell swr to re-validate your data with mutation. This is a example from SWR documentation. It shows how to automatically refetch the login info (e.g. inside <Profile/>) 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 new todo. But every time you add 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 same 3 request to the API. That is totally unnecessary. It will take more data and will cause unneccessary 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 use with Both rest and graphql: SWR does not fetch the data. The fetcher function does. And that's allow 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 loading state to the user.

Reusable code: SWR is itself a hook. And you can create custom hook from hooks. It allow us to write DRY(don't repeat yourself) code. Suppose you want to fetch data from /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 settings 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. I also some other features.

  • Built in Typescript support.
  • Fast, lightweight.
  • Tree shaking available.

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

Shameless Plug

Want to create your own blog? Well, I am creating a video series where you will learn about how to create a JAMstack blog with Nextjs and Chakra-UI.

Lessons

Demo

You can demo the website from here

Features

  • Static Blog pages will make the website load faster.
  • Blogs will have code blocks with syntax highlighting and many embed components like youtube videos, GitHub gist, Tweets, and so many other things.
  • Autocomplete search feature for the blog posts.
  • Real-time view counter and so on.

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

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

By the way, I am looking for a new opportunity in a company where I can provide great value with my skills. If you are a recruiter, looking for someone skilled in full-stack web development and passionate about revolutionizing the world, feel free to contact me. Also, I am open to talking about any freelance project. I am available on Upwork

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostTop 5 state management libraries for React
Next PostEasily toggle between light and dark theme with Material-UI