Movies app using react-query for server-side state management
Rishikesh Vedpathak
Posted on May 16, 2021
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.
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
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
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,
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
Fetch movies using React Query(useQuery hook)
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,
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.
You can see the queries cached in devtools,
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,
You searched ‘Batman’ for the very first time. It will fetch data from API and while fetching, the application will display loader on UI.
Now you clear the search box and searched for ‘Marvel’, the same will happen.
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.
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.
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 for React app development services.