Chat with us
  • 13 November 2025

Getting Started with React Query (TanStack Query)

by Rankush – 3 minute read – Published 13 November 2025 – Updated 26 November 2026 – 117 views

Quick answer: Use TanStack Query v5 and Axios to load a list of posts in a React TypeScript app. A shared query key lets components read the same cached response and update it in the background.

Getting Started with React Query (TanStack Query) script preview image

Use TanStack Query v5 and Axios to load a list of posts in a React TypeScript app. A shared query key lets components read the same cached response and update it in the background.

What the example covers

  • Fetch posts with a typed query function and show loading and error states.
  • Reuse fresh data for one minute by setting staleTime.
  • Keep previously loaded posts visible while a background fetch runs.

In the fast-moving world of custom website development, managing data effectively has become crucial for creating high-performing web applications. React Query (now known as TanStack Query) is a robust library that streamlines data fetching, caching, synchronization, and server state management in your React web app.

Whether you’re providing website development services or planning to hire a React developer, mastering React Query can greatly improve the efficiency and reliability of your React-based projects.

Features of React Query

1. Data Caching

React Query automatically stores fetched data and reuses it to prevent redundant API calls, improving both performance and user experience.

2. Error Handling

  • Handles API errors internally for seamless interactions with your backend.
  • Reduces the need for manual try-catch blocks or repetitive error-handling logic.

3. State Management

No need to manually manage server-side state using hooks like useEffect. React Query automatically tracks loading, success, and error states, keeping your app’s UI perfectly in sync with your data.

For teams providing website development services, this means faster development cycles and fewer bugs.

Prerequisites

Before diving in, make sure you meet the following requirements:

  • Comprehension of JavaScript syntax
  • Basic knowledge of the React.js framework
  • Understanding of APIs
  • A React 18 or later project with TypeScript and npm

Navigate to your React project directory and run the following command in your terminal:

                                        npm install @tanstack/react-query@5 axios@1
                                    

If you plan to hire a React developer, ensure they are comfortable with these tools as they’re foundational for modern React-based custom website development.

Set up the query client in src/App.tsx

To make React Query available globally, you need to wrap your entire app inside a QueryClientProvider. This allows all components to share the same query client and benefit from global caching and synchronization.

Code Example

                                        import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

import DisplayPosts from "./display-post";

const queryClient = new QueryClient();

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

export default App;
                                    

This setup is an important step in any React project, especially for developers working on dynamic website development services that require smooth API integrations.

Performing Data Fetching

The useQuery hook in React Query makes fetching and managing server data incredibly simple.
Below, we’ll use Axios to retrieve posts from an external API. If the data is still loading or an error occurs, appropriate messages are displayed; otherwise, the posts are rendered as a list.

Save the component below as src/display-post.tsx. The array ["posts"] identifies the collection. For one minute, a component using the same key can reuse the fresh result. A later mount, reconnect or return to the tab can refresh stale data in the background.

Code Example

                                        import axios from "axios";
import { useQuery } from "@tanstack/react-query";

interface Post {
  id: number;
  title: string;
}

async function retrievePosts(signal: AbortSignal): Promise<Post[]> {
  const response = await axios.get<Post[]>(
    "https://jsonplaceholder.typicode.com/posts",
    { signal }
  );
  return response.data;
}

export default function DisplayPosts() {
  const query = useQuery({
    queryKey: ["posts"],
    queryFn: ({ signal }) => retrievePosts(signal),
    staleTime: 60_000,
  });

  if (query.isPending) return <p>Loading posts…</p>;
  if (query.isError && !query.data) return <p role="alert">{query.error.message}</p>;

  return (
    <>
      {query.isFetching && <p role="status">Refreshing posts…</p>}
      {query.isRefetchError && <p role="alert">Refresh failed. Showing the last result.</p>}
      <ul>
        {query.data?.map((post) => <li key={post.id}>{post.title}</li>)}
      </ul>
    </>
  );
}
                                    

When you run this code in your browser, you’ll see a neatly rendered list of post titles fetched directly from the API.

This example demonstrates how React Query makes custom website development smoother by automating the complexities of data fetching and state synchronization.

On Success

Once the posts are successfully fetched, the browser will display a list of post titles like below:

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

qui est esse

ea molestias quasi exercitationem repellat qui ipsa sit aut

eum et est occaecati

nesciunt quas odio

dolorem eum magni eos aperiam quia

magnam facilis autem

dolorem dolore est ipsam

nesciunt iure omnis dolorem tempora et accusantium

optio molestias id quia eum

Freshness, retries and cleanup in v5

  • staleTime controls how long a result stays fresh. The default is zero. This example uses 60,000 milliseconds.
  • gcTime controls how long an unused query stays in the cache. The browser default is five minutes. Use refetchInterval if you need polling.
  • retry defaults to three retries for failed client queries. Set it to zero when testing an immediate error state.
  • For pagination, import keepPreviousData and set placeholderData: keepPreviousData to display the last page while the next loads.
  • Use isPending, isError and isFetching to render query state. Query-level success and error callbacks were removed in v5.

To check the example, open the network panel and load the list. Switch tabs and return within one minute, then repeat after the data becomes stale. Compare the network requests and the posts already on screen. See the TanStack Query defaults.

Why React Query Is a Must-Have for Modern Web Apps

React Query bridges the gap between client and server data, making custom website development more scalable, maintainable, and user-friendly. If your business offers website development services, integrating React Query can reduce boilerplate code, improve performance, and create a more responsive experience UI.

For those hiring a React developer, selecting someone skilled in TanStack Query guarantees your projects are built with modern, efficient practices that follow today’s best web development standards.

Final Words

React Query (TanStack Query) revolutionizes how React developers handle server state management. It automates the complexities of data fetching, caching, and synchronization, allowing developers to focus on building features rather than managing state manually.

Whether you’re an agency offering website development services, working on custom website projects, or planning to hire a React developer, integrating React Query will streamline your workflow and improve your app’s performance.

Tech Stack & Version

Frontend

  • React.js
  • React Query
  • CSS / Tailwind

Backend

  • Node.js
  • Express.js

Deployment

  • Netlify
  • Vercel