Introduction to React Query

Introduction to React Query

A beginners guide.

As a react developer it's hard for us to create our method of data fetching. Because we may need to use different hooks and thus there is no predetermined way of fetching or updating data in components. There comes the use of React Query.

What is React Query?

React Query is a server-state management library. Just like the React Query docs say, it makes fetching, caching, synchronising and updating server-state in your React application a breeze. It's used to cache, update and invalidate data based on server-side updates.

Why React Query?

Most of the state management libraries are great for working with client state, they are not so great at working with async or server state. React Query helps with caching, updating "Out of date" data in the background, performance optimizations like pagination and lazy loading data etc. Other than that it offers different states like isLoading, isError, success, isFetching for an API call. It supports Prefetching, Mutations, Pagination / Infinite scroll, retry on an error which acts as a great functionality of React Query.

Enough of the talk, now let's make a request using React Query. But before that let's see the prerequisites and project setup.

Prerequisite

  • A beginner's knowledge of React and Javascript.

  • The basic idea of fetching data using fetch or Axios in React.

Setting up the App and installing dependencies

We will be making use of create-react-app. To create your app run the below command in the terminal :

npx create-react-app react-query-app

Now start the app by running the following commands:

cd react-query-app
npm start

This will run our development server at localhost:3000

Now along with that, we need to install React Query. So type this command in the terminal:

npm install react-query

Making a request using React Query

We will be making use of JSON placeholder API as the endpoint(JSONplaceholder).

Now create a component folder inside the src directory and create 2 files Post.js and PostDetails.js. In the App.js file clear all the jsx and just set up an h1 tag with Hello World(<h1>Hello World</h1>).In Post.js just make an h1 tag with Blog post as the content (<h1>Blog post</h1>).

Now in the App.js create a Query Client Provider which is wrapped around Post Component. Query Client and Query Client Provider are imported from react-query. React Query Devtools is imported from react-query-dev tools. Now create a queryClient (const queryClient = new QueryClient()). It creates an instance of query client which help in the query. We will include ReactQueryDevtools, which helps in monitoring different queries. By default, it's not included in production. You can read more about react-query-dev tools here. Thus our app will now look like this:

Now in Post.js :

Now here "posts" is the unique key for that Query. It is called the Query key. Along with that, we provide a call-back function that gives return data after the API call.

Here fetchPosts is the call-back function which returns the data. The endpoint here is posts. Here isLoading,isError,isFetching, and error are different states during fetch and "data" is the variable where the API data is stored.

Now if we return the JSX based on different conditions:

Thus if all these conditions don't work out then the data is ready and thus we can show the data. Here we will return the data as an unordered list of titles.

Now this is how we make an API request using React Query.

Query Keys

It's a unique key to a query. It is an individual string or array of keys used to make the Query more unique. Thus an example of it will be ["Post",2]. It means that it's referring to 2nd post or something. It simply means the number of serialisable objects.

Query key as a Dependency

Now let's try to make changes such that on clicking an item on the list we get its description at the bottom.

Create a new file called PostDetails.js in the components folder. Only when a post is clicked, then only we need to show the details of that Post ( Here we show the email and body associated with the post). Thus create a state like this in Post.js to track if a post is clicked or not.

Now our Post.js will look like this.

Now in PostDetails file, we try to fetch the API and show them using the key "post details".

The fetching of the API is like this (Note: post is the props that we passed in ):

Now if you try hitting another post this won't change the data, this is because we are calling the same "post details" key API. This doesn't change the API call, because initially the key was set and we didn't change the key on each API call. This happens because react query looks for a query key to check if a query is to be called. Here the query key is "post details" whose data is the data that we got in the first hit. As the query key is the same react query takes the same data and doesn't hit that API again. Thus we need to have a strategy such that the key changes on clicking each post. So we change the query key to ["post details", post.id]. Thus on clicking the 2nd post, we get the key as ["post details",2] thus that API is hit. This works the same as the useEffect with a dependency. But react query stores the data in the cache and thus prevent it from hitting the API again and again.

If you have reached this far I think you have done great. This was just a small introduction to react query. There are plenty of things that you can do including pagination, mutations, pagination and more.