Discover the Magic of ‘useQuery’: Easily Get, Store, Sync, and Update Data in Your React Components. No More Complex Redux! This Library Streamlines Caching and Updating, Solving Tricky Server State Issues. Explore this User-Friendly Gem: It’s Simple at First Glance, Yet Surprisingly Packed with Solutions for Your App’s Data Management.”
React Query provides us with custom hooks like “useQuery” for retrieving data. Under the hood, these hooks do a lot of things such as caching data after initial retrieval, fetching data in the background, etc.
React Query is undoubtedly one of the best libraries for managing server states. It works amazingly well, right out of the box, with no configuration, and can be customized to your liking as your app grows.
When working with an API, there are many things you want to keep in mind, such as the loading status and the state of the data. While most traditional state management libraries are great for working with client states, they are not so great for working with async or server side states.
Once you are working with server state in your app then you will find many issue like below
React Query allows you to master and overcome the tough challenges and hurdles of server state and control your application data before they start controlling you technically, React Query is probably:
In this article, I’ll show you how to use the useQuery hook to retrieve data. For this I use the JSON placeholder as an API endpoint to retrieve data.
Start the this tutorial with installing react-query in your react app.
npm i --save react-query
Then I clean up App.js and write the fetchUsers function to fetch data from the API. The function looks like this. I use fetch(). But we can also use Axios or other methods.
//FetchApi.js
import axios from "axios";
const fetchUsers = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
};
export default fetchUsers;
Now import the useQuery from react-query.
import { useQuery } from "react-query";
And now we can use the “useQuery” hook to manage data retrieval as shown below,
const response = useQuery("users", fetchUsers);
useQuery hook requires two arguments, the first is a key to this query. I use String “users” for this. We can also specify an array as the first argument. If an array is passed, each element is serialized into a stable query key. The second is a function to retrieve the data.
I’ve included the fetchUsers asynchronous function that I created earlier. Also, we can pass an object as the third argument for various options and it is optional. useQuery given us the some response when we are calling the any request with useQuery. Following are some response we are getting.
“data” is the actual data we received. “status” is “loading“, “error“, “successful” or “idle” depending on the response. And all these properties have different uses. For more information on the useQuery hook, see the official documentation
.So I destruct the useQuery response as below and use the “data” and “status” properties for data retrieval.
const { data, status } = useQuery("users", fetchUsers);
As I explain you above following is the complete code
import React from "react";
import './app.css';
import { useQuery } from "react-query";
import fetchUsers from './FetchApi';
const App = () => {
const { data, status } = useQuery("users", fetchUsers);
return (
<div className="App">
{status === "error" && <p>Error fetching data</p>}
{status === "loading" && <p>Fetching data...</p>}
{status === "success" && (
<div>
{data.map((user) => (
<p key={user.id}>{user.name}</p>
))}
</div>
)}
</div>
);
};
export default App;
This is a simple explanation of how we can use React Query’s useQuery hook. There are also many other hooks. You must try it
Introduction Git tags are an essential feature of version control systems, offering a simple way…
Introduction The methods that browsers employ to store data on a user's device are referred…
Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…
Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…
Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…
Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…