SWR or React-Query? What to use? | Aakash Bhardwaj

SWR or React-Query? What to use?

Hey everyone,

I hope you are having a terrific day today. Today, I was working on a Next.js project and I was wondering what to use for async state management. I explored two options. SWR provided by Vercel and React-query. Let's talk about these options in detail.

media

React-Query

React-query is a powerful async state management which comes with a powerful cache layer. The main focus is to keep server/client state in sync. It offers queries and mutations while also providing loading and error states which is quite useful. Let's see an example:-

function App() { const mutation = useMutation(newTodo => { return axios.post('/todos', newTodo) }) return ( <div> {mutation.isLoading ? ( 'Adding todo...' ) : ( <> {mutation.isError ? ( <div>An error occurred: {mutation.error.message}</div> ) : null} {mutation.isSuccess ? <div>Todo added!</div> : null} <button onClick={() => { mutation.mutate({ id: new Date(), title: 'Do Laundry' }) }} > Create Todo </button> </> )} </div> )}

In the code snippet above, we can see how we can initiate a mutation with the help of an action. A post request using axios was initiated. A mutation can only be in one of the following states at any given moment:

isIdle or status === 'idle' - The mutation is currently idle or in a fresh/reset state

isLoading or status === 'loading' - The mutation is currently running

isError or status === 'error' - The mutation encountered an error

isSuccess or status === 'success' - The mutation was successful and mutation data is available

For queries, they run immediately without any user action. Now let's talk about SWR. SWR provides hooks for data fetching. Extremely lightweight and provides a strategy to first return the data from cache, then send the fetch request (revalidate), and finally come with the up-to-date data.

As soon as I read a little bit about SWR, I quickly installed it. And then I realised that its main use case is to fetch data only. But I need more things than that. I think SWR provides a great alternative for the most basic data fetching techniques that we do traditionally using a useEffect. If that's our use case, then it's a perfect solution.

But what about the mutations section in the SWR docs?

While browsing through the SWR docs, I saw a section on mutations and I quickly jumped to the conclusion that they do provide an alternative to make requests other than simple data fetching. But as soon as I read that section, I realised that it was a completely different concept.

They should really change this. It's quite misleading. Anyway, let me share with you what it actually is. Let's have a look at this particular code snippet:-

import useSWR, { useSWRConfig } from 'swr'function App () { const { mutate } = useSWRConfig() 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> )}

So mutate in the above example does not make an api call to that particular end point. What it does is that it tells the existing hooks in your app is to refetch this data in the app if it exists. After reading this, I was left with a surprised pikachu face. I had to remove this package and replace it with React-query because it gives me more stuff.

media

Anyway, I hope you had fun reading this. See you tomorrow. Ciao!


Tagged users
editor-img
Aryan Agarwal
@aryankush25
Technical Lead | Driving Innovation at Glue Labs | Ex - Software Development Engineer at GeekyAnts Just Learning New Things!! 😉