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
Managing Pagination, Caching, and Background Refetch0%
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 IntermediateManaging Pagination, Caching, and Background Refetch
React Re-render Rules and Profiling Bottlenecks

Managing Pagination, Caching, and Background Refetch

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

1. The Challenges of Server-Side Pagination

When dealing with databases containing thousands of courses, orders, or logs, sending the entire dataset in a single JSON payload degrades network latency and browser memory.

Backend APIs slice data using pagination (e.g. ?page=1&limit=10).

In traditional React, handling pagination creates visual flickering: when a user clicks "Next Page", the old data disappears, a loading spinner flashes, and the new page appears.

TanStack Query provides advanced primitives to manage pagination, stale caches, and background refetching smoothly without UI layout thrashing.

1Traditional Pagination:
2[Page 1 Data] ──(Click Next)──► [Blank Spinner Flash!] ──► [Page 2 Data]
3 
4TanStack Query (keepPreviousData):
5[Page 1 Data] ──(Click Next)──► [Keep Page 1 visible while Page 2 loads in background] ──► [Instant Page 2 Swap!]

2. Paginated Queries with placeholderData: keepPreviousData

In TanStack Query (v5+), passing placeholderData: keepPreviousData keeps the previous page's data on screen while the new page is being fetched:

1import React, { useState } from 'react';
2import { useQuery, keepPreviousData } from '@tanstack/react-query';
3 
4async function fetchStudentsPage(page = 1) {
5 const res = await fetch(`/api/students?page=${page}&limit=10`);
6 if (!res.ok) throw new Error('Network error');
7 return res.json();
8}
9 
10export default function PaginatedStudentDirectory() {
11 const [page, setPage] = useState(1);
12 
13 const {
14 data,
15 isLoading,
16 isError,
17 isPlaceholderData // True while previous page data is being shown as a placeholder!
18 } = useQuery({
19 queryKey: ['students', page], // Key includes 'page' so each page is cached independently!
20 queryFn: () => fetchStudentsPage(page),
21 placeholderData: keepPreviousData // Smooth pagination transition!
22 });
23 
24 if (isLoading) return <div className="spinner">Loading initial page...</div>;
25 if (isError) return <div>Failed to load student directory.</div>;
26 
27 return (
28 <div className="directory-box">
29 <h2>Registered Students (Page {page})</h2>
30 
31 {/* Render current or placeholder data */}
32 <ul className={`student-list ${isPlaceholderData ? 'opacity-50' : ''}`}>
33 {data.students.map((student) => (
34 <li key={student.id}>{student.name} — {student.track}</li>
35 ))}
36 </ul>
37 
38 {/* Pagination Controls */}
39 <div className="pagination-bar">
40 <button
41 onClick={() => setPage((old) => Math.max(old - 1, 1))}
42 disabled={page === 1}
43 >
44 ← Previous
45 </button>
46 
47 <span>Page {page} of {data.totalPages}</span>
48 
49 <button
50 onClick={() => {
51 if (!isPlaceholderData && page < data.totalPages) {
52 setPage((old) => old + 1);
53 }
54 }}
55 disabled={isPlaceholderData || page >= data.totalPages}
56 >
57 Next →
58 </button>
59 </div>
60 </div>
61 );
62}

3. Cache Invalidation with queryClient.invalidateQueries

When a user adds, edits, or deletes an item on the server via an HTTP mutation, the cached data in other views becomes stale.

Rather than trying to manually locate and modify complex nested cached data structures, you tell TanStack Query to invalidate the query key:

1import { useMutation, useQueryClient } from '@tanstack/react-query';
2 
3export function useAddStudent() {
4 const queryClient = useQueryClient();
5 
6 return useMutation({
7 mutationFn: (newStudent) => {
8 return fetch('/api/students', {
9 method: 'POST',
10 headers: { 'Content-Type': 'application/json' },
11 body: JSON.stringify(newStudent)
12 });
13 },
14 // On success: invalidate all queries matching the 'students' key!
15 onSuccess: () => {
16 queryClient.invalidateQueries({ queryKey: ['students'] });
17 }
18 });
19}

Invoking invalidateQueries marks matching cached queries as stale and immediately triggers an automatic background refetch for any active components on screen!


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why should the page state variable be included in the queryKey: ['students', page] array?
Question 2
What visual problem does placeholderData: keepPreviousData solve during pagination?
Question 3
What function is used to instruct TanStack Query to refresh stale data after a successful mutation?
Question 4
How can you indicate to users that data currently visible on screen is transitional placeholder data while the next page is loading?
Question 5
If a user visits Page 1, navigates to Page 2, and then clicks "Previous" back to Page 1, what does TanStack Query do?
Next Lesson

React Re-render Rules and Profiling Bottlenecks

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

Related Lessons

Previous LessonNext Lesson
Introduction to TanStack Query for Server StateReact Re-render Rules and Profiling Bottlenecks

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