Movies app using react-query for server-side state management
Tags: react, reactquery, reactstatemanagement, javascript
Published: 2021-05-16 18:37:40

State management is one of the key factors that developers should consider before starting a React project. React developers usually tend to use libraries like Redux for a solution and with that, they often misuse the way the redux should be used.

In this article, we will see how react-query helps solve the issues we face with redux and the practical example to demonstrate the use case of react-query.

Here is the [demo application](https://react-query-movies-app.netlify.app/) we are going to discuss,

{% youtube Q92YalYbfkM %}

## What is React Query?
>  React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze.
[**React Query**](https://react-query.tanstack.com/)

React Query changes the way we look at our application state. It introduces the concepts of **Client state** and **Server state**. While using redux, we often put all the state to redux store even the local state like if a sidebar is open or not. React Query allows you to defeat and overcome the tricky challenges and hurdles of server state and control your app data before it starts to control you.

Key features of React Query,

* Help you remove **many** lines of complicated and misunderstood code from your application and replace them with just a handful of lines of React Query logic.

* Make your application more maintainable and easier to build new features without worrying about wiring up new server state data sources

* Have a direct impact on your end-users by making your application feel faster and more responsive than ever before.

* Potentially help you save on bandwidth and increase memory performance

## Installation

You can install React Query with **NPM **or **Yarn**,

    npm i react-query 

or

    yarn add react-query

## Devtools for React Query

React Query does come with dedicated devtools. The devtools are bundle split into the react-query/devtools. Just import it into your app.js file as,

    import { ReactQueryDevtools } from 'react-query/devtools'

By default, React Query Devtools are not included in production bundles when process.env.NODE_ENV === 'production', so you don't need to worry about excluding them during a production build.

Once imported, wrap your root component with QueryClientProvider

{% gist https://gist.github.com/RishikeshVedpathak/aa7f8fa0aa8c7daa26490624f36e3ace %}

Now, when you run your application locally it will show a small react-query icon in the bottom-left corner and when you click on it opens up a devtools as shown below,

![React Query Devtools](https://cdn-images-1.medium.com/max/3810/1*6BfuqOOH_RrrVI7g4ZRI-Q.png)

The devtools has many other options which we can configure at our convenience. Refer to [https://react-query.tanstack.com/devtools](https://react-query.tanstack.com/devtools) for more details.

## OMDb API

For this project, we are using the OMDb API. It is a free web service to obtain movie information. It is simple to use and the doc page is pretty easy to understand. However it just provides the GET APIs, so we won’t be able to perform POST/PUT/DELETE operations.
[**OMDb API**](https://www.omdbapi.com/)

## Fetch movies using React Query(useQuery hook)
{% gist https://gist.github.com/RishikeshVedpathak/d595a87309d5597b67adb5a04537c74c.js %}
Yes, it is as simple as it looks. The useQuery returns a few very important states.

* isLoading or status === 'loading' - The query has no data and is currently fetching

* isError or status === 'error' - The query encountered an error

* isSuccess or status === 'success' - The query was successful and data is available

* isIdle or status === 'idle' - The query is currently disabled (you'll learn more about this in a bit)

Beyond those primary states, more information is available depending on the state of the query:

* error - If the query is in an isError state, the error is available via the error property.

* data - If the query is in a success state, the data is available via the data property.

* isFetching - In any state, if the query is fetching at any time (including background refetching) isFetching will be true.

Using these states we can decide what to display on UI,
{% gist https://gist.github.com/RishikeshVedpathak/b7f76c8b4b52d4ebd3ad072504ae8685.js %}
## Query Keys

Consider a scenario where we want to fetch movies depending on the search text. For this, we need to pass search text as a query parameter to our GET API. We can achieve this with the help of query keys.
>  At its core, React Query manages query caching for you based on query keys. Query keys can be as simple as a string, or as complex as an array of many strings and nested objects. As long as the query key is serializable, and **unique to the query’s data**, you can use it!

In our case, the query key is a simple string value.
{% gist https://gist.github.com/RishikeshVedpathak/1d7ed180ac7d78f5e91057f98e4cda68.js %}
You can see the queries cached in devtools,

![](https://cdn-images-1.medium.com/max/3806/1*VDrIJSXftTwqW8cl6SyiQA.png)

## Understanding Caching

The query key that we have provided to our useQuery hook is used internally for refetching, caching, and sharing your queries throughout your application.

To understand this let's see the below steps,

 1. You searched ‘Batman’ for the very first time. It will fetch data from API and while fetching, the application will display loader on UI.

 2. Now you clear the search box and searched for ‘Marvel’, the same will happen.

 3. You again clear the search box and searched for ‘Batman’ again, in this case, you will see search results are displayed immediately without any wait time and loader on UI. This is because React query managed to cache the data for the unique key i.e. [“movies”, “Batman”].
And React Query intelligently updates the data returned from the second API call in its cached data.

 4. This improves our application performance.

## Conclusion

React Query is a powerful and easy-to-use library to manage our application’s server state. It is a great alternative to Redux, MobX and can reduce boilerplate code to a larger extent. React Query is not a replacement for local/client state management. However, you can use React Query alongside most client state managers with zero issues.

We have created a Movie List Application just using React Query to demonstrate its use case. We did not use any other state management library which concludes the importance of keeping client and server states separately.

You can find the final code in the GitHub repo,
{% github https://github.com/RishikeshVedpathak/react-query-movies-app %}

I hope this will help you to understand and encourage you to freely use React Query in your application. Please feel free to give feedback and suggestions!

### And more...
- Check [Hybrowlabs](https://hybrowlabs.com/react-js-dev-outsourcing) for React app development services.