React Query data fetching library for beginners.

Muhammad Haris
3 min readOct 1, 2020

React query is a new tool introduced to handle the fetching of data from the server in a react app. React Query library helps user to synchronizing, caching and updating the server state without any pain. In traditional react application user have to create their own logic to fetch data from the server and to cache data (possibly the hardest thing to do in programming).

Enough talk let’s get some hand dirty on code :)

First of all install updated version of node from https://nodejs.org/en/ then create a new react js application and install react-query dependencies by using the follow commands,

npx create-react-app myapp
cd myapp
npm i react-query or if you are using yarn (yarn add react-query)

In this app we will use star wars api to perform api calls https://swapi.dev/ .

Our program structure will look like this,

Now we will write some logic :

We will toggle between two pages by using ternary operator if the showPlanet is true it will return Planet component else it will return People component.

First of all I import useQuery from the react-query library, useQuery accepts two or more parameter, the first parameter is the key of query you can name it as you like then the second parameter is an async method which will return the response from the server.
useQuery returns data and status (useQuery also return other values but for now we will focus on data and status), status has three states which are loading, success and error. If the data is fetching from the server it will return loading string, if the data is fetched from the server it will return the success
string and response will store in data variable, if the server will throw an error then the status will return an error.

As you can see in this image,

If the status is loading I return the loading, if the status is an error I return the error and if the status is success then I map the data from the data variable.

We will perform the same logic in Planet component and it will look like this :

Now we can toggle between components and you will observed that if the data is fetched it will not require any loading because the data is cached.

This is the planet tab
This is the people tab.

I hope you like this tutorial and it will help you and moreover if you want to learn more about react-query you can read the documentation. https://react-query.tanstack.com/docs/overview.

--

--