Under the Hood
The story begins when I continuous saw the new post about react query and its power of caching the data and re-fetching it whenever required. This blows my mind because we do have to write the caching logic in the frontend or we have to use Redis in the backend to maintain the cache data.
But React Query comes with the upper hand on this issue, they provide easy custom hooks and a root provider to get started as quickly as possible.
Getting Started
In today’s story, we will not be going much into detail about React Query instead I am attaching the link to read more about react query from their docs itself. The documentation is not difficult to understand so I would recommend reading it once.
https://react-query.tanstack.com/overview
3 Steps to Quickly start with React Query
- Install the React Query package using yarn or npm
- Wrap Query provider to the root of the application and provide client as a prop
- Fetch sample data using the useQuery hook provided by React Query
Adding React Query package
This is simple and pretty straightforward, depending on your package version manager uses either npm or yarn.
yarn add react-queryThe best part about this package is, you don’t really need other package dependencies like Redis or local storage something else.
Wrapping provider to root of the application
Since we are using Next JS the entire root of the application can be wrapped inside _app.js, if you are using Create React App then inside src/index.js you can wrap the provider.
The provider can be imported from the react-query package itself and wrapped just like Higher Order Components to the root of the application.
Another part is to provide the client with a prop to the QueryClientProvider. React Query provide QueryClient method to get the client object in return which we can simply pass a prop to QueryClientProvider.
import { QueryClientProvider, QueryClient } from 'react-query';
function MyApp({ Component, pageProps }) {
const queryClient = new QueryClient();
return (
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
</QueryClientProvider>
);
};
export default MyAppFetching Sample Data
Inside the components folder, I’ve added a component called AllPost which will display the list of all the posts from an API. We will be again using the sample API provided by JSON placeholder API.
JSON placeholder Posts API Endpoint
Using axios we will fetch the data and decoupled the entire data fetching logic inside api folder in packages directory.
import axios from 'axios';
const getAllPostUrl = "https://jsonplaceholder.typicode.com/posts";
export default async function getAllPost(){
const response = await axios.get(getAllPostUrl);
return response.data;
};Once the data fetching logic is written, we will be using useQuery the method of react-query to get the status of data fetching like is data fetched or fetching.
useQuery
This hook takes 2 parameters as an argument, one is the string key which helps the react-query to cache and re-fetch the data and the second argument is the API method or data fetching method that returns a promise.
useQuery hooks provide 2/4 things in return and those are as follows-
- isLoading— Signifies that data is still in loading state
- isError — Return the error in fetching data from the API
- data — The data object when everything went well
Although useQuery provides other details too but these 3 key parameters are mostly used and enough to handle all edge cases.
import React from "react";
import getAllPost from "../Packages/api/getAllPost";
import { useQuery } from "react-query";
const AllPost = () => {
const {
isLoading,
isError,
data,
error
} = useQuery('allPost', getAllPost);
if(isLoading){
return <p>Loading....</p>
}
if(isError){
return <p>{error.message}</p>
}
return (
<div className="h-screen">
<p>Post</p>
<div>
{data.map(item => {
return (
<div>
<p>Title:{" "}<span>{item.title}</span></p>
<p>Body:{" "} <span>{item.body}</span></p>
</div>
);
})}
</div>
</div>
)};
export default AllPost;If you saw the code in few lines of code we have fetched almost 100 posts from the endpoint and if we refresh the application on the browser it uses the cache data to improve performance and load the data faster.
Devtools
This is quite useful and powerful, just importing one line of code helps you to view the status of the entire data fetching endpoint.

React Query dev tools running in the localhost
This provides a way to refetch, validate and reset the data to see the changes in the UI accordingly. This is quite helpful as being a developer you don’t have to console the data every time and see the changes to debug or trace down the errors.
Conclusion
React Query is good and powerful and its application for large-scale applications with other state management libraries and Redis is still on hold. But I am confident about the product as they have covered a big problem for you to improve performance in the frontend application.
React Query is available in React Native also which I will cover in the next story, so stay tuned and don’t forget to follow me. Until next time, have a good day, people.
