Handling “global” state in React using React Query.

Adetoyese Kola-Balogun
2 min readMay 31, 2022
Tanstack React Query logo

Redux is excellent for managing client state because it enables data synchronisation across the entire app, minimises prop digging, and makes it clearer when state changes take place. However, in most cases, Redux isn’t used appropriately. In a lot of React applications, Redux, which is a client side state manager is also is used to store server data. This process is anti pattern and this is where React Query comes in. React Query is an asynchronous server state manager used to fetch, store, cache and manage server side data.

React Query’s concept is to handle the vast majority of server-side state in an all-in-one manner by retrieving, re-retrieving, storing, caching, updating, and memoizing it. With other combined client- and server-side state management tools, a lot of the boilerplate that inevitably develops is reduced by these separations.

The library also offers some cutting-edge capabilities like “optimistic updates,” which make the app appear to be responsive and simple to use by making an assumption about a data update’s success before actually receiving a response from the back end.

Let’s take a look at how to get started with react query. First, let’s install as a dependency in a project.

npm install react-query

Next, I’m going to import the QueryClient and QueryClientProvider and wrap the entire application within it.

import React from 'react';
import { QueryClientProvider, QueryClient } from 'react-query';
const queryClient = new QueryClient();const App = () => {
return (
<QueryClientProvider client={queryClient}>
<div className="App">
<h1>React App Homepage</h1>
</div>
</QueryClientProvider>
);
}
export default App;

In the code example above, I instantiated a queryClient instant with the QueryClient constructor. I then passed the queryClient into a client prop and wrapped the entire application with the QueryClientProvider.

Next, I’m going to make a simple API request to fetch some data using react query.

import { useQuery } from "react-query";export const UserListComponent = () => {
const getUsers = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (response.ok) {
return response.json();
} else {
throw new Error("An error occurred");
}
} catch (e) {
console.error(e);
}
};
const { data } = useQuery("users", getUsers);return (
<ul>
{data?.map((user) => (
<div>
<h3>{user.name}</h3>
</div>
))}
</ul>
);
};

In the UserListComponent, I created a function getUsers to make an asynchronous request to fetch users data. I then passed the getUsers function and a key “users”, as an argument into react query’s useQuery hook. In this example, react query handle the fetching, error handling, cache, storage and re-fetching of the user data.

--

--

Adetoyese Kola-Balogun

Software Developer | React Expert | Building financial software solutions.