MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Introduction to TanStack Query for Server State0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
7.1Fetching REST APIs with Async Await and State7.2Handling HTTP POST, PUT, and DELETE Mutations7.3Introduction to TanStack Query for Server State7.4Managing Pagination, Caching, and Background Refetch
HomeTutorialsReact.js for IntermediateIntroduction to TanStack Query for Server State
Managing Pagination, Caching, and Background Refetch

Introduction to TanStack Query for Server State

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. The Server State vs Client State Paradigm

In React development, engineers historically treated all data the same—dumping both UI state and fetched API data into useState, useReducer, or Redux.

However, modern engineering distinguishes between two fundamentally different types of state:

  1. 1
    Client State (UI State): Data wholly owned by the browser that is synchronous and always up-to-date (e.g. modal open/closed, active tab, form inputs).
  2. 2
    Server State (Remote Cache): Data owned by a remote server that is asynchronous, shared across multiple users, requires serialization, and can become stale at any moment without your knowledge (e.g. user profile, course list, stock prices).

Using raw useEffect and useState for server state forces you to manually write hundreds of lines for caching, deduplication, retry logic, background refetching, and pagination.

TanStack Query (formerly React Query) is the industry standard for managing server state in modern web applications.

1Traditional useEffect Data Fetching:
2[Manual loading state] + [Manual error state] + [No caching] + [No auto-retry] + [Race conditions]
3 
4TanStack Query:
5const { data, isLoading, error } = useQuery(...)
6(Automatic caching, window-focus refetching, background updates, auto-retries!)

2. Installing TanStack Query

1npm install @tanstack/react-query

3. Setting Up QueryClientProvider

Wrap your application root with QueryClientProvider:

1// src/main.jsx or src/App.jsx
2import React from 'react';
3import ReactDOM from 'react-dom/client';
4import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
5import App from './App.jsx';
6 
7// Create a query client instance
8const queryClient = new QueryClient({
9 defaultOptions: {
10 queries: {
11 staleTime: 1000 * 60 * 5, // Data remains "fresh" for 5 minutes
12 retry: 2 // Automatically retry failed requests twice
13 }
14 }
15});
16 
17ReactDOM.createRoot(document.getElementById('root')).render(
18 <React.StrictMode>
19 <QueryClientProvider client={queryClient}>
20 <App />
21 </QueryClientProvider>
22 </React.StrictMode>
23);

4. Fetching Data with useQuery

To fetch and cache data, call the useQuery hook:

1import React from 'react';
2import { useQuery } from '@tanstack/react-query';
3 
4async function fetchCourses() {
5 const res = await fetch('/api/courses');
6 if (!res.ok) throw new Error('Network response was not ok');
7 return res.json();
8}
9 
10export default function CourseDirectory() {
11 // queryKey uniquely identifies this cache entry
12 // queryFn is the promise-returning function
13 const { data: courses, isLoading, isError, error } = useQuery({
14 queryKey: ['courses'],
15 queryFn: fetchCourses
16 });
17 
18 if (isLoading) return <div className="spinner">Fetching courses...</div>;
19 if (isError) return <div className="error-alert">Error: {error.message}</div>;
20 
21 return (
22 <div className="course-list">
23 <h2>Active Courses ({courses.length})</h2>
24 <ul>
25 {courses.map(course => (
26 <li key={course.id}>{course.title}</li>
27 ))}
28 </ul>
29 </div>
30 );
31}

5. Superpowers Out of the Box

By adopting TanStack Query:

  • Automatic Caching: If two components request ['courses'], only one network request is sent!
  • Window Focus Refetching: When a user tabs back to your application after reading an email, TanStack Query automatically refreshes stale data in the background.
  • Deduplication: Multiple rapid calls are merged into a single network flight.

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary difference between Client State and Server State?
Question 2
What are the two mandatory properties required when configuring useQuery?
Question 3
What happens by default when two separate components on the same screen both invoke useQuery({ queryKey: ['userData'], ... })?
Question 4
What does staleTime configure in TanStack Query?
Question 5
What component must wrap your application tree to enable TanStack Query hooks?
Next Lesson

Managing Pagination, Caching, and Background Refetch

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Handling HTTP POST, PUT, and DELETE MutationsManaging Pagination, Caching, and Background Refetch

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext