How to use React query in reactjs with example

Atiq ur rehman
2 min readMar 17, 2023

React Query is a popular library for managing remote data in React applications. It simplifies the process of fetching, caching, and updating data from APIs by providing a set of hooks and utilities that can be used to handle data in a declarative way.

React Query

Here’s an example of how to use React Query in a React application:

  1. Install React Query as a dependency in your project:
npm install react-query

Import QueryClientProvider and QueryClient from react-query in your application's root component:

import { QueryClient, QueryClientProvider } from 'react-query';
import React from 'react';

const queryClient = new QueryClient();

function App() {
return (
<QueryClientProvider client={queryClient}>
{/* your application components */}
</QueryClientProvider>
);
}

This creates a new instance of QueryClient and provides it to your application's components via the QueryClientProvider.

2. Define a React Query hook to fetch data from an API. For example, let’s say you have an API endpoint that returns a list of users:

import { useQuery } from 'react-query';
import axios from 'axios';

function fetchUsers() {
return axios.get('/api/users').then(res => res.data);
}

function Users() {
const { isLoading, data, error } = useQuery('users', fetchUsers);

if (isLoading) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error fetching users: {error.message}</div>;
}

return (
<div>
{data.map(user => (
<div key={user.id}>
{user.name} ({user.email})
</div>
))}
</div>
);
}

This hook uses useQuery to fetch data from the /api/users endpoint and returns a loading state, the fetched data, and any errors that occur. The useQuery hook takes two arguments: the key for the query ('users' in this case), and the function that fetches the data (fetchUsers).

3. Render the Users component in your application:

function App() {
return (
<QueryClientProvider client={queryClient}>
<Users />
</QueryClientProvider>
);
}

This will render the Users component and trigger the useQuery hook to fetch data from the API.

That’s it! With just a few lines of code, you’ve set up a React Query client, defined a hook to fetch data from an API, and used that hook in a React component to display the data. React Query takes care of caching the data and keeping it up to date as it changes on the server, so you can focus on building your application.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Atiq ur rehman
Atiq ur rehman

No responses yet

Write a response