Fetching Data From Public API using React Query.
An effortless and efficient way to fetch data.
React Query is a powerful library that simplifies data fetching, caching, and state management in React applications.
In this tutorial, I’ll guide you through setting up a React project using Vite and dive deep into using React Query to fetch data from a public API (https://randomuser.me/). By the end of this tutorial, you’ll not only have a working React Query setup but also a comprehensive understanding of its core functions and features.
Let’s get started.
Prerequisites
Before we begin, make sure you have Node.js and npm installed on your machine. You can download them from https://nodejs.org/.
Step 1: Project Setup with Vite
Vite is a fast, opinionated frontend build tool that makes it easy to set up a new React project. Open your terminal and run the following commands:
# Create a new React project with Vite
npm create vite@latest react-query-demo --template react
# Change into the project directory
cd react-query-demo
# Install dependencies
npm install
Set 2: Install React Query
Now that our project is set up, let’s install React Query:
# Install React Query
npm install react-query
Open your project in VS Code and then we can proceed.
Set 3: Create a Component to Fetch Data
In the src
directory, create a components folder and create a new file within it named DataFetchingComponent.js
. Open the file and create a React component that uses React Query's useQuery
hook to fetch data.
// src/components/DataFetchingComponent.js
import { useQuery } from 'react-query';
const fetchData = async () => {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
return data;
};
const DataFetchingComponent = () => {
const { data, isLoading, error } = useQuery('exampleQuery', fetchData);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Name: <br/> <span>{`${data.results[0].name.first} ${data.results[0].name.last}`}</span></h1>
<img src={data.results[0].picture.large} alt={data.results[0].name.first} />
</div>
);
};
export default DataFetchingComponent;
The useQuery
hook takes two main parameters: the query key and the function responsible for fetching the data (fetchData
in our example). The query key is a unique identifier for the query and is used internally by React Query.
- Query Key: The first argument
useQuery
is the query key, which is a string or an array of strings. It helps React Query uniquely identify this query and cache its results. - Data Fetching Function: The second argument is the function that performs the actual data fetching. This function can be asynchronous and should return the data.
How React Query Works
One of the key advantages of React Query is that you don’t need to manually run it inside a useEffect
hook. React Query manages the data fetching lifecycle for you. When your component renders, React Query automatically initiates the data fetching process. This simplifies your code and eliminates the need for manual data-fetching logic.
Data Caching in React Query
React Query provides powerful data caching capabilities out of the box. When you use the useQuery
hook, React Query automatically caches the results. Subsequent renders of the component that uses the same query key will trigger a re-render with the cached data, eliminating the need to re-fetch data unnecessarily.
This caching mechanism not only enhances performance by reducing unnecessary network requests but also provides a seamless user experience. React Query intelligently manages cache invalidation, ensuring that your UI always reflects the latest data.
Step 4: Use the Fetch Data Component in App.jsx
Now, let’s use the DataFetchingComponent
in the App.js
file:
// src/App.js
import React from 'react';
import DataFetchingComponent from './DataFetchingComponent';
function App() {
return (
<div className='app'>
<h1>React Query Tutorial</h1>
<DataFetchingComponent />
</div>
);
}
export default App;
Step 5: Create a React Query Client
In your App.jsx
file, import, and configure QueryClient
from react-query and then wrap the entire App Component’s JSX with QueryClientProvider
import {QueryClient, QueryClientProvider} from 'react-query';
import DataFetchingComponent from "./components/DataFetchingComponent";
import './App.css';
function App(){
const queryClient = new QueryClient();
return(
<QueryClientProvider client={queryClient}>
<div className='app'>
<h1>React Query Tutorial</h1>
<DataFetchingComponent />
</div>
</QueryClientProvider>
)
}
export default App;
Understanding the Query Client
The QueryClient
plays a crucial role in managing the state and configuration of your queries. It is responsible for caching, background re-fetching, and keeping track of the various queries within your application. By wrapping your application with QueryClientProvider
and providing the QueryClient
instance, you enable React Query to efficiently manage the state of your queries.
Importance of the Query Client
- Global Configuration: The
QueryClient
allows you to configure default options for all queries, providing a consistent behavior across your application. For instance, you can set a default cache time or specify the number of retries for failed queries. - Query Invalidation: The
QueryClient
is aware of all the queries in your application. When data changes, you can easily invalidate specific queries, prompting React Query to re-fetch and update the UI accordingly. - Devtools Integration: The
QueryClient
integrates with the React Query Devtools, providing a powerful debugging tool to inspect and interact with your queries in real-time. - Optimistic Updates: The
QueryClient
facilitates optimistic updates, allowing you to instantly reflect the expected result of a mutation in the UI before receiving confirmation from the server.
By leveraging the QueryClient
, you streamline the management of queries and enhance the overall performance and user experience of your React application.
Step 6: Start the Development Server and Test the App
Run the following command to start the Vite development server:
The output should look like this.
From the output, we can see that the name and picture of a random person were retrieved from the API. 🎉
Congratulations! You’ve successfully set up a React project using Vite, integrated React Query to fetch data from a public API, and properly configured a QueryClient
.
I hope you have learned how to use React Query.
Reference:
Check out the project code base using this link
Happy Coding!