My experience with React Query

Aravind S
2 min readJul 5, 2021
react-query-tanstack

I would like to share my experience using React Query for Fetch, cache and update data in your React application. In one my project, the requirement was how we can avoid unnecessary API calls if the data is stale. That exploration lead to React Query.

My Observations:

  1. Bye bye to setState : With React Query we can get rid of multiple setStates. For example, if we get to get a data from an API, we need a try catch block, setState to save data, loader, error handler and useEffect hooks.
//Component did mount
useEffect(()=>{
try{
//Handle the loader
//Handle the async API Call
}catch(error){
//Handle the error scenario
}
},[]);

the above code can be re written in React Query as:

const { isLoading, isError, data } = useQuery('uniqueKey', () =>fetch('API URL').then(res =>res.json()));

React Query will provide constants like isLoading, isError, data which can be used in the UI. Check out the other constants for useQuery here: https://react-query.tanstack.com/reference/useQuery

2. It also provides a lot of other feature like :

★ staleTime : Time after the API have to refetch. Default is zero and. If we mention 500 more time means data will be stale for 500ms.

★ refetchOnWindowFocus : refetch the API when window is focussed again.

★ onSuccess, onError, onSettled : For handling success, error and settled scenarios.

Checkout the other important defaults here : https://react-query.tanstack.com/guides/important-defaults

3. Mutating data : Unlike queries, mutations are typically used to create/update/delete data . For this purpose, React Query exports a useMutation hook.

Above points are just a quick glance and its worth checking it out more here : https://react-query.tanstack.com/

Happy Reading!

--

--