React Query — Multiverse of API Calls

Arun Yokesh
3 min readApr 5, 2022
Photo by Scott Goodwill on Unsplash

React Query

It acts as a API call manager, Backend may be anything but this will help us fetch, cache and update data in your react applications without touching any “global state”.

React Query follows GraphQL like structure where query is for fetching the data and mutation for updating the data. By this way we are getting to know graphQL functionalities and usage. For the store you can use either Apollo Store or Context API or Redux. But redux is making the application complex on top of it, we need to use the Redux thunk for asynchronous operations.

Why React Query is Good for Asynchronous API calls:

  • Auto Caching
  • Can run multiple parallel queries at the same time
  • Easy to handle all type of API’s like REST, GraphQL, Promises etc
  • Multi-layer Cache + Automatic Garbage Collection
  • Refetching — It automatically retires for 3 times before the error is shown in the UI
  • API calls will be in organised way. Increases Readability.
  • Getting REST API Data’s in a structured format like data, error, status, isLoading and it can be access in the render part directly.
  • It has Devtools for debugging. it will be easy to identify the issues.
  • It will reduce the usage of useState hook. we can directly access the API data const { data } = useQuery("posts", usePosts); in the render part.
  • Load-More + Infinite Scroll Queries and many more

React Query Caching

async function usePosts() {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return data;
}
const { status, data, error, isFetching, isLoading }
= useQuery("posts", usePosts);

This is the simple example of React Query and how it is getting used. Once the data is loaded from the API. It will be stored in cache (cache by default its having 5 minutes of expire and its configurable). For the further requests, the data will be loaded from cache. For each call, Simultaneously it will Make an API call, If the data is changed then it will update cache also it will reflect on UI. Nothing will happen if the data’s are same.

  • data — returns REST API data
  • error — any error occurred during the request
  • status — status of the request
  • isLoading — requesting for the first time and waiting for response from server
  • isFetching — Refreshing the cache from backend / refetching the response to update cache.

By default, “inactive” queries are garbage collected after 5 minutes.

Queries that fail are silently retried 3 times, with exponential backoff delay before capturing and displaying an error to the UI.

Query — Fetching

async function usePosts() {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return data;
}
const { status, data, error, isFetching, isLoading } = useQuery("posts", usePosts);

Mutation — Updating

async function createPost(params) {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', params)
setMessage(response.data)
}
const { mutate, isLoading } = useMutation(createPost, {
onSuccess: data => {
console.log(data);
},
onError: () => {
alert("there was an error")
},
});
const onSubmit = (params) => {
mutate(params);
};

For Devtools, need to add the following component

<ReactQueryDevtools initialIsOpen />

Initial component should be wrapped with to get the react query functionality in the child components. QueryClient is used to interact with the cache data. It can be accessed in the child components by useQueryClient hook.

<QueryClientProvider client={queryClient}> 
// Child components
</QueryClientProvider>

--

--