Enable Dark Mode!
overview-of-react-query-for-beginners.jpg
By: Alan Joy

Overview of React Query for Beginners

Technical Odoo 18

If you’ve ever built a React app that fetches data from an API, you’ve probably dealt with state management, loading indicators, error handling, and re-fetching. Doing all of this manually with useEffect and useState can get messy quickly, especially in larger apps.

That’s where React Query comes in.

React Query is a game-changer for data fetching in React. It simplifies the process, handles caching, keeps your UI in sync with your data, and even supports features like background updates and pagination — all out of the box.

In this post, we’ll explore React Query from a beginner’s perspective and show you how to get started.

What is React Query?

React Query (also known as TanStack Query) is a data-fetching library for React that focuses on:

* Fetching

* Caching

* Synchronizing

* Updating server state

It helps you manage remote data the way React manages local state — cleanly and reactively.

Why Not Just useEffect + useState?

Sure, useEffect and useState can handle API calls, but they quickly become cumbersome. For example, to fetch data and handle loading, success, and error states, you might write something like this:

const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
  fetch('https://api.example.com/posts')
    .then((res) => res.json())
    .then(setData)
    .catch(setError)
    .finally(() => setLoading(false));
}, []);

This works, but what if you want to refetch data automatically? Or cache it? Or manage multiple queries?

React Query does all of that — with way less code.

Getting Started with React Query

Let’s set up a simple React project with React Query and fetch some data.

Step 1: Install React Query

First, install the package:

npm install @tanstack/react-query

Or with Yarn:

yarn add @tanstack/react-query

Step 2: Set Up the Query Client

React Query needs a QueryClient to manage caching and queries across your app.

In index.js (or main.jsx if you're using Vite), wrap your app with QueryClientProvider:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query';
const queryClient = new QueryClient();
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Step 3: Fetch Data Using useQuery

Now let’s fetch data inside your App.js:

import React from 'react';
import { useQuery } from '@tanstack/react-query';
const fetchPosts = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
};
function App() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['posts'],
    queryFn: fetchPosts,
  });
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return (
    <div style={{ padding: '20px' }}>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>
            <strong>{post.title}</strong>
          </li>
        ))}
      </ul>
    </div>
  );
}
export default App;

That’s it!

No need to manage state, loading flags, or manual error handling. React Query takes care of it all.

Features That Make React Query Awesome

Here are some of the powerful features that React Query gives you with minimal setup:

* Caching

Data is cached and reused — no need to refetch unless you want to.

* Refetching

Data can automatically refetch on window focus or network reconnect.

// Refetch every 5 seconds
useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts,
  refetchInterval: 5000,
});

* Query Keys

Query keys help you uniquely identify each query. They're also used for invalidation and refetching.

* Pagination and Infinite Scrolling

React Query supports pagination out of the box with useInfiniteQuery.

* Mutations (For POST/PUT/DELETE Requests)

React Query isn’t just for fetching. You can also handle creating, updating, and deleting data with useMutation.

Bonus: Devtools for Debugging

React Query has a great set of devtools to help you debug queries:

npm install @tanstack/react-query-devtools

Then add it to your app:

import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
<QueryClientProvider client={queryClient}>
  <App />
  <ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>

It will show a panel with your active queries, their status, and cached data. Super helpful!

Final Thoughts

React Query is an incredible tool that brings structure and power to your data-fetching needs in React. Whether you’re constructing a small app or a large-scale project, React Query:

* Reduces boilerplate

* Handles background updates

* Improves performance through caching

* Simplifies your code

If you’ve ever been frustrated juggling state, loading indicators, and manual fetch calls — React Query will feel like magic.

To read more about What are the Key Features in React 19, refer to our blog What are the Key Features in React 19.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message