What is React Query

CodingWithDavid
3 min readMay 5, 2022

--

React Query is “Performant and powerful data synchronization for React” (“https://react-query.tanstack.com/”), but what does that mean and why do we care? React Query helps us to take data from a promise, typically made with a fetch to an API, and store, cache, and update it in the background when needed.

I used React Query for the first time in my last project and was truly impressed that it worked so well for my needs. Not only did it provide a state for my API fetch, it also provided a ton of functionality by default that reduced the amount of code I would have to write.

I am sure that we are all used to having to write something like this:

import React, {useState} from 'react'
import axios from 'axios'
function App(){
const [animals, setAnimals] = useState({})
const [isLoading, setIsLoading] = useState(false)
const fetchAnimals = async () => {
setIsLoading(true);
try {
const data = await axios.get('/api/animals').then((r) => r.data)
setAnimals(data);
setIsLoading(false)
} catch (error) {
console.log(error);
}
}
useEffect(() =>{
fetchAnimals();
}, [])
if (isLoading) {
return <div> Loading... </div>
}
return (
{whatever it is you want to display}
)
}

That is a lot of code just to get a fetch. What happens if an animal is added or removed, then that data is useless and another call fetchAnimals must be made.

Well with React Query we could refactor that code to something similar to this:

import React from 'react'
import axios from 'axios'
import {useQuery} from 'react-query'
function App(){
[data, isLoading] = useQuery('animals',()=> axios.get('/api /animals').then((r)=>r.data),
)
if (isLoading){
return <div>Loading...</div>
return ({whatever you want to display})
}

Not only is that much short, but we also gain a ton of features and even gain a performance boost. There is no need to have additional state to store your data in, in fact you wouldn’t to use it because it that state would have stale data in it eventually. We also gain the ability to use different statuses like: isLoading, isError, isSuccess, isIdle, and isFetching.

When we use our data React Query will provide you instantly with the cached data and then run a fetch in the background to see if anything changed. If there was a change it would push that to your component in a rerender. If nothing changes then you will benefit from much faster load times than you would if you fetched that data a traditional way.

If you are writing a but of code that you know will require a fetch to get new data, you can simply add one line to force a refetch from that specific query. To do so you would need to import QueryClient then most people use const queryClient = QueryClient() then simply add queryClient.invalidateQueries('animals') to your code. You can obviously replace 'animals' with any “key” you would like so long as it aligns with the “key” used to make the fetch. Additionally you can have dynamic “keys” like this, useQuery(['book',page],fetchFunction) then you have the choice to invalidate all 'book' queries or just the specific page you want.

React Query treats “keys” like useEffect treats dependencies which makes keeping your data synchronized easy.

After using this package in my last project, I can confidently say that it will be incorporated in nearly every personal project I do going forward.

Want to learn more about React Query?

Also if you don’t already, you might want to follow Tanner Linsley at https://github.com/tannerlinsley. he is the creator or React Query and more amazing open source packages.

--

--