My experience with React Query

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
//Handle the loader
//Handle the async API Call
//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:

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 :

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 :

Happy Reading!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store