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.

1import useSWR, { mutate } from 'swr'
2
3function App () {
4 return (
5 <div>
6 <Profile />
7 <button onClick={() => {
8 // set the cookie as expired
9 document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
10
11 // tell all SWRs with this key to revalidate
12 mutate('/api/user')
13 }}>
14 Logout
15 </button>
16 </div>
17 )
18}
  • 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.

1function useUser() {
2 return useSWR('/api/user', fetcher)
3}
4
5function Avatar() {
6 const { data, error } = useUser()
7
8 if (error) return <Error />
9 if (!data) return <Spinner />
10
11 return <img src={data.avatar_url} />
12}
13
14function App() {
15 return (
16 <>
17 <Avatar />
18 <Avatar />
19 <Avatar />
20 <Avatar />
21 <Avatar />
22 </>
23 )
24}

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.

1function App() {
2 const { data, error, isValidating } = useSWR('/users', fetcher)
3 return <>.... </>
4}
5
6// instead
7function useUser() {
8 return useSWR('/users', fetcher)
9}
10
11function App() {
12 const { data, error, isValidating } = useUser()
13 return <>.... </>
14}
  • 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

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

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

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