Mastering React Query: The Ultimate Guide to Server State Management

Introduction

React Query (now TanStack Query) has become an essential library for managing server state in modern React applications. Unlike client state (like form inputs or UI toggles), server state has unique characteristics: it's asynchronous, can become stale, and is shared across components. React Query handles these complexities elegantly, making data fetching feel almost magical.

To grasp the idea in a glance, have a look to this component and its annotation : https://github.com/HPWebdeveloper/react-query/blob/main/src/components/FetchDataReactQuery.tsx

Why React Query?

Traditional data fetching in React involves managing loading states, error handling, and caching manually. This leads to boilerplate code scattered throughout your application. React Query abstracts these concerns and provides:

  • Automatic caching - Data is cached by default and shared across components
  • Background refetching - Keep data fresh automatically
  • Optimistic updates - Update UI immediately before server confirms
  • Request deduplication - Multiple components requesting the same data trigger only one request
  • Pagination & infinite scrolling - Built-in support with simple APIs

Getting Started

First, install React Query:

npm install @tanstack/react-query

Set up the QueryClient and Provider in your app root:

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

const queryClient = new QueryClient()

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

Basic Data Fetching with useQuery

The useQuery hook is your primary tool for fetching data:

import { useQuery } from '@tanstack/react-query'

function UserProfile({ userId }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then((res) => res.json()),
  })

  if (isLoading) return <div>Loading...</div>
  if (error) return <div>Error: {error.message}</div>

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  )
}

The queryKey is crucial - it uniquely identifies this query for caching. When the key changes (e.g., different userId), React Query automatically refetches.

Mutations with useMutation

For creating, updating, or deleting data, use useMutation:

import { useMutation, useQueryClient } from '@tanstack/react-query'

function EditUser({ userId }) {
  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn: (updatedUser) => {
      return fetch(`/api/users/${userId}`, {
        method: 'PUT',
        body: JSON.stringify(updatedUser),
        headers: { 'Content-Type': 'application/json' },
      })
    },
    onSuccess: () => {
      // Invalidate and refetch user data
      queryClient.invalidateQueries({ queryKey: ['user', userId] })
    },
  })

  const handleSubmit = (formData) => {
    mutation.mutate(formData)
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? 'Saving...' : 'Save'}