JavaScript and React course ยท Module 10: React Ecosystem and Future
React Query / TanStack Query - Modern Server State Management
In this lesson6
The mission panel shows an astronaut's profile in three components at once. With useEffect and fetch, each one sends a separate request, none of them remembers the result, and switching profiles quickly can show data belonging to the wrong person. React Query, today called TanStack Query, changes the way you fetch, cache and synchronize server state with the UI. Like a navigation system that tracks the ship's position by itself, the library manages the state of your data on its own.
Why React Query Instead of useEffect + fetch?
Look at the traditional approach and the list of its problems in the comments:
// Traditional approach - MANY PROBLEMS
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, [userId]);
// Problems:
// 1. No caching - same data fetched multiple times
// 2. No automatic refetching
// 3. No optimistic updates
// 4. No request deduplication
// 5. No stale data handling
// 6. Must manually manage loading/error states
// 7. Race condition issues
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{user.name}</div>;
}You manage the loading and error states by hand, and when userId changes quickly an older response can overwrite a newer one, which is a race condition. Nothing here is cached or deduplicated.
The same component with TanStack Query looks like this:
// React Query - ELEGANT AND POWERFUL
import { useQuery } from '@tanstack/react-query';
function UserProfile({ userId }) {
const { data: user, isPending, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json())
});
if (isPending) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{user.name}</div>;
}Every query needs two things: queryKey, a unique key in the cache, and queryFn, a function that returns a promise with the data. The ['user', userId] key gives each user a separate entry, and three components with the same key will send one request. isPending means there is no data yet, so after both checks user is defined. Remember that fetch does not throw an error on a 404 or 500 status, so check res.ok, as createMission does below.
Installation and Basic Configuration
You install the main package and the optional developer tools:
# Installing TanStack Query (React Query v5)
npm install @tanstack/react-query
npm install @tanstack/react-query-devtools # Optional DevToolsDevTools end up in the bundle only in development mode, so you do not have to remove them before deploying.
QueryClient stores the cache and the default query options, and QueryClientProvider makes it available to the application:
// App.jsx - Setup QueryClient
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
// Create Query Client with configuration
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes
gcTime: 1000 * 60 * 30, // 30 minutes
refetchOnWindowFocus: true,
refetchOnReconnect: true,
retry: 3,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
{/* DevTools - visible only in development */}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}staleTime says how long data stays fresh, and gcTime (cacheTime in version 4) after what time an unused entry disappears from memory. By default staleTime is 0 and gcTime is 5 minutes.
The Query Lifecycle: status and fetchStatus
The stale-while-revalidate strategy means that you show data from the cache immediately, even if it is stale, while in the background the library fetches fresh data and swaps it into the UI. To tell what is happening at any moment, TanStack Query v5 describes a query with two independent fields. status is about the data: pending (there is none yet, loading in version 4), error or success. fetchStatus is about the queryFn function: fetching (it is running), paused (it wants to fetch, but there is no network) or idle (it is doing nothing). The idle and loading values of status no longer exist:
function MissionCounter() {
const { data, status, fetchStatus, isStale } = useQuery({
queryKey: ['missions'],
queryFn: fetchMissions,
staleTime: 30 * 1000, // Data stays fresh for 30 seconds
});
if (status === 'pending') return <p>First load (fetchStatus: {fetchStatus})</p>;
if (status === 'error') return <p>Failed to fetch missions</p>;
return (
<p>
Missions: {data.length}, data is {isStale ? 'stale' : 'fresh'}
{fetchStatus === 'fetching' && ' - refreshing in the background'}
</p>
);
}This is the typical path of a query from the moment the component mounts:
- Mount - there is no data, so
statusispendingandfetchStatusisfetching. Only in this situation isisLoading, meaningisPending && isFetching,true. - Success - the data has arrived:
statuschanges tosuccessandfetchStatustoidle. For thestaleTimeperiod the data is fresh and the library sends no new requests. - Stale data - once
staleTimepasses, the data becomes stale (isStaleistrue), but that alone does not fetch anything yet. By defaultstaleTimeis 0, so data is stale right after it is fetched. - Background refresh - a trigger, such as a new component with the same key, returning to the browser tab (
refetchOnWindowFocus), the network reconnecting (refetchOnReconnect) orinvalidateQueries, starts a fetch.statusstayssuccessand the old data is still visible, whilefetchStatuschanges tofetching, soisFetchingistrueandisLoadingisfalse. - Idle again - the fresh data replaces the old data,
fetchStatusgoes back toidle, and thestaleTimecountdown starts over.
Without a network the query does not fail, it switches to fetchStatus: 'paused' and resumes by itself once the connection is back. refetchInterval refreshes data periodically, independently of staleTime.
useMutation - POST, PUT, DELETE requests
Queries read data, and mutations change it. useMutation takes a mutationFn and sends nothing by itself, it only returns an object with a mutate method:
import { useMutation, useQueryClient } from '@tanstack/react-query';
async function createMission(newMission) {
const response = await fetch('/api/missions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newMission),
});
if (!response.ok) {
throw new Error('Failed to create mission');
}
return response.json();
}
function CreateMissionForm() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: createMission,
// Optimistic update
onMutate: async (newMission) => {
await queryClient.cancelQueries({ queryKey: ['missions'] });
const previousMissions = queryClient.getQueryData(['missions']);
queryClient.setQueryData(['missions'], (old) => [...old, newMission]);
return { previousMissions };
},
// Rollback on error
onError: (err, newMission, context) => {
queryClient.setQueryData(['missions'], context.previousMissions);
},
// Invalidate and refetch
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['missions'] });
},
});
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
mutation.mutate({
name: formData.get('name'),
destination: formData.get('destination'),
date: formData.get('date'),
});
};
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Mission name" required />
<input name="destination" placeholder="Mission destination" required />
<input name="date" type="date" required />
<button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? 'Creating...' : 'Create Mission'}
</button>
</form>
);
}This is an optimistic update: onMutate immediately adds the mission to the cache, before the server responds, and remembers the previous list. On error, onError restores it from context, and onSettled invalidates the ['missions'] key, so the list syncs with the server either way. cancelQueries stops an ongoing fetch so it does not overwrite the change, and isPending disables the button.
Pagination with React Query
With pagination the page number goes into the key, so each page has a separate entry in the cache:
import { useQuery, keepPreviousData } from '@tanstack/react-query';
function PaginatedMissions() {
const [page, setPage] = useState(1);
const { data, isLoading, isPlaceholderData } = useQuery({
queryKey: ['missions', page],
queryFn: () => fetchMissions(page),
placeholderData: keepPreviousData,
});
return (
<div>
{isLoading ? (
<div>Loading...</div>
) : (
<>
<div className="missions-list">
{data.missions.map(mission => (
<div key={mission.id} className="mission-item">
<h3>{mission.name}</h3>
</div>
))}
</div>
<div className="pagination">
<button
onClick={() => setPage(old => Math.max(old - 1, 1))}
disabled={page === 1}
>
Previous
</button>
<span>Page {page} of {data.totalPages}</span>
<button
onClick={() => setPage(old => old + 1)}
disabled={isPlaceholderData || page >= data.totalPages}
>
Next
</button>
</div>
</>
)}
</div>
);
}placeholderData: keepPreviousData keeps the previous page on screen until the next one arrives, so the list does not flicker. isPlaceholderData tells you that you are still seeing old data, which is why the Next button waits.
Infinite Queries - Infinite Scrolling
useInfiniteQuery stores all the fetched pages of an infinite list in data.pages:
import { useInfiniteQuery } from '@tanstack/react-query';
function InfiniteMissions() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
status,
} = useInfiniteQuery({
queryKey: ['infiniteMissions'],
queryFn: ({ pageParam }) => fetch(`/api/missions?page=${pageParam}&limit=20`).then(r => r.json()),
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) => {
return lastPage.hasMore ? allPages.length + 1 : undefined;
},
});
if (status === 'pending') return <div>Loading...</div>;
if (status === 'error') return <div>Loading error</div>;
return (
<div>
<div className="infinite-list">
{data.pages.map((page, i) => (
<React.Fragment key={i}>
{page.missions.map(mission => (
<div key={mission.id} className="mission-card">
<h3>{mission.name}</h3>
</div>
))}
</React.Fragment>
))}
</div>
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage
? 'Loading...'
: hasNextPage
? 'Load More'
: 'No more data'}
</button>
</div>
);
}initialPageParam (mandatory in version 5) sets the first page, and getNextPageParam returns the next page number or undefined when the data runs out, which sets hasNextPage to false.
I recommend keeping server data in TanStack Query, and only UI state, like open panels, in useState or Redux, because these are two different kinds of state. The library automates fetching, caching, synchronizing and updating data like an autopilot that corrects its course by itself, while you focus on the user experience. It will come in handy in every project with an API, because queryFn can be any function that returns a promise, including a GraphQL client.
Remember: a query key is a set of coordinates in the cache - the same coordinates mean the same data, and stale data refreshes in the background. In the example below, watch the status and fetchStatus fields: wait 5 seconds until the data goes stale, return to the tab, and then add a mission, also with a simulated server error.
Code for this lesson: App.jsx
import { useEffect, useState, useSyncExternalStore } from 'react';
// === TanStack Query v5 - a simplified cache simulation ===
// In a project: npm install @tanstack/react-query and useQuery({ queryKey, queryFn, staleTime }).
// This mini client shows the same fields as the library: status (pending | error | success),
// fetchStatus (fetching | paused | idle), and fresh or stale data once staleTime passes.
const STALE_TIME = 5000; // Data stays fresh for 5 seconds
const startedAt = Date.now();
// A fake server with a list of missions
let serverMissions = [
{ id: 1, name: 'Apollo-RQ1', status: 'active', crew: 4 },
{ id: 2, name: 'Nebula-X7', status: 'completed', crew: 6 },
{ id: 3, name: 'Orion-3', status: 'planned', crew: 3 },
];
const api = {
getMissions: () => new Promise(resolve => setTimeout(() => resolve([...serverMissions]), 800)),
addMission: (mission, fail) => new Promise((resolve, reject) => setTimeout(() => {
if (fail) {
reject(new Error('The server rejected the mission'));
return;
}
const saved = { ...mission, id: Date.now() };
serverMissions = [...serverMissions, saved];
resolve(saved);
}, 700)),
};
// The cache entry for the ['missions'] key - QueryClient does this for you
function createQuery(queryFn) {
let state = { status: 'pending', fetchStatus: 'idle', data: undefined, error: null, dataUpdatedAt: 0, isStale: true, log: [] };
let inFlight = null;
let fetchId = 0;
let staleTimer = null;
const listeners = new Set();
const setState = (patch, message) => {
const time = ((Date.now() - startedAt) / 1000).toFixed(1) + ' s';
const log = message ? [...state.log, { time, message }].slice(-10) : state.log;
state = { ...state, ...patch, log };
listeners.forEach(listener => listener());
};
const markFresh = (data, message) => {
clearTimeout(staleTimer);
setState({ status: 'success', data, error: null, dataUpdatedAt: Date.now(), isStale: false, fetchStatus: 'idle' }, message);
staleTimer = setTimeout(() => setState({ isStale: true }, 'staleTime passed: data is stale, but nothing is fetched yet'), STALE_TIME);
};
const query = {
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getState() {
return state;
},
fetch(reason) {
if (inFlight) return inFlight; // Deduplication: one request at a time
if (state.status === 'success') {
setState({ fetchStatus: 'fetching' }, 'fetchStatus: fetching, status still success - background refresh (' + reason + ')');
} else {
setState({ fetchStatus: 'fetching' }, 'status: pending, fetchStatus: fetching - first load (isLoading: true)');
}
const id = ++fetchId;
inFlight = queryFn()
.then(data => {
if (id === fetchId) markFresh(data, 'status: success, fetchStatus: idle - data fresh for ' + STALE_TIME / 1000 + ' s');
})
.catch(error => {
if (id === fetchId) setState({ status: 'error', error, fetchStatus: 'idle' }, 'status: error - ' + error.message);
})
.finally(() => {
if (id === fetchId) inFlight = null;
});
return inFlight;
},
// cancelQueries: the result of the ongoing fetch will be ignored
cancel() {
if (!inFlight) return;
fetchId++;
inFlight = null;
setState({ fetchStatus: 'idle' }, 'cancelQueries: the ongoing fetch was cancelled');
},
refetchIfStale(reason) {
if (state.isStale) query.fetch(reason);
else if (state.status === 'success') setState({}, reason + ': data is fresh, so no new request');
},
invalidate(reason) {
clearTimeout(staleTimer);
setState({ isStale: true });
return query.fetch(reason);
},
setData(updater, message) {
markFresh(updater(state.data), message);
},
};
return query;
}
const missionsQuery = createQuery(api.getMissions);
// The equivalent of useQuery({ queryKey: ['missions'], queryFn, staleTime: 5000 })
function useMissionsQuery() {
const state = useSyncExternalStore(missionsQuery.subscribe, missionsQuery.getState);
// Component mount: fetch if there is no data or it is stale
useEffect(() => {
missionsQuery.refetchIfStale('new component');
}, []);
// refetchOnWindowFocus: returning to the tab refreshes only stale data
useEffect(() => {
const onFocus = () => missionsQuery.refetchIfStale('window focus');
window.addEventListener('focus', onFocus);
return () => window.removeEventListener('focus', onFocus);
}, []);
return {
...state,
isPending: state.status === 'pending',
isFetching: state.fetchStatus === 'fetching',
isLoading: state.status === 'pending' && state.fetchStatus === 'fetching',
};
}
function Badge({ label, value, color }) {
return (
<span style={{ ...styles.badge, borderColor: color, color }}>
{label}: <strong>{String(value)}</strong>
</span>
);
}
function QueryStatus({ query }) {
return (
<div style={styles.card}>
<div style={styles.badges}>
<Badge label="status" value={query.status} color="#00d4ff" />
<Badge label="fetchStatus" value={query.fetchStatus} color={query.isFetching ? '#ffa500' : '#8892b0'} />
<Badge label="isLoading" value={query.isLoading} color="#8892b0" />
<Badge label="isFetching" value={query.isFetching} color="#8892b0" />
<Badge label="data" value={query.isStale ? 'stale' : 'fresh'} color={query.isStale ? '#ff6b6b' : '#00ff88'} />
</div>
<div style={styles.staleTrack}>
{!query.isStale && <div key={query.dataUpdatedAt} style={styles.staleFill} />}
</div>
<div style={styles.buttons}>
<button style={styles.button} onClick={() => missionsQuery.refetchIfStale('window focus')}>
Simulate returning to the tab
</button>
<button style={styles.button} onClick={() => missionsQuery.invalidate('invalidateQueries')}>
invalidateQueries(['missions'])
</button>
</div>
</div>
);
}
function AddMission({ ready }) {
const [name, setName] = useState('');
const [failServer, setFailServer] = useState(false);
const [isPending, setIsPending] = useState(false);
// The equivalent of useMutation with an optimistic update
const addMission = async () => {
const mission = { name: name.trim(), status: 'planned', crew: 2 };
if (!mission.name || isPending || !ready) return;
setName('');
setIsPending(true);
// onMutate: cancel the ongoing fetch, remember the list and add the mission right away
missionsQuery.cancel();
const previous = missionsQuery.getState().data;
missionsQuery.setData(old => [...old, { ...mission, id: 'temp-' + Date.now(), optimistic: true }], 'onMutate: mission added optimistically');
try {
await api.addMission(mission, failServer);
} catch (error) {
// onError: restore the list from before the change
missionsQuery.setData(() => previous, 'onError: ' + error.message + ' - the previous list was restored');
} finally {
// onSettled: invalidate the key to sync with the server
setIsPending(false);
missionsQuery.invalidate('onSettled');
}
};
return (
<div style={styles.form}>
<input
value={name}
onChange={e => setName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && addMission()}
placeholder="New mission name..."
style={styles.input}
/>
<button onClick={addMission} disabled={isPending || !ready} style={styles.primary}>
{isPending ? 'Saving...' : 'Add mission'}
</button>
<label style={styles.check}>
<input type="checkbox" checked={failServer} onChange={e => setFailServer(e.target.checked)} />
Simulate a server error
</label>
</div>
);
}
export default function App() {
const query = useMissionsQuery();
return (
<div style={styles.page}>
<div style={{ maxWidth: '640px', margin: '0 auto' }}>
<h1 style={styles.title}>TanStack Query v5 - the query lifecycle</h1>
<p style={styles.subtitle}>staleTime: {STALE_TIME / 1000} s. Wait until the data goes stale, then return to the tab.</p>
<QueryStatus query={query} />
<div style={styles.card}>
{query.isPending ? (
<p style={styles.muted}>Loading missions...</p>
) : query.status === 'error' ? (
<p style={{ color: '#ff6b6b' }}>Error: {query.error.message}</p>
) : (
query.data.map(m => (
<div key={m.id} style={{ ...styles.mission, opacity: m.optimistic ? 0.6 : 1 }}>
<strong>{m.name}</strong>
<span style={styles.muted}>
{m.optimistic ? 'saving (optimistic)' : m.status + ', crew: ' + m.crew}
</span>
</div>
))
)}
<AddMission ready={query.status === 'success'} />
</div>
<div style={styles.card}>
<h3 style={styles.logTitle}>Query log</h3>
{query.log.map((entry, i) => (
<div key={i} style={styles.logRow}>
<span style={styles.logTime}>{entry.time}</span>
<span>{entry.message}</span>
</div>
))}
</div>
</div>
<style>{'@keyframes staleCountdown { from { width: 100%; } to { width: 0%; } }'}</style>
</div>
);
}
const styles = {
page: { minHeight: '100vh', background: 'linear-gradient(135deg, #0a0e27 0%, #1a1a3e 100%)', padding: '20px', color: '#e0e1dd', fontFamily: 'system-ui, sans-serif', fontSize: '13px' },
title: { textAlign: 'center', color: '#00d4ff', margin: '0 0 6px', fontSize: '20px' },
subtitle: { textAlign: 'center', color: '#8892b0', margin: '0 0 14px' },
card: { background: 'rgba(0,0,0,0.3)', border: '1px solid rgba(0,212,255,0.15)', borderRadius: '10px', padding: '12px', marginBottom: '12px' },
badges: { display: 'flex', flexWrap: 'wrap', gap: '6px' },
badge: { border: '1px solid', borderRadius: '6px', padding: '3px 8px', fontSize: '12px' },
staleTrack: { height: '4px', background: 'rgba(255,255,255,0.08)', borderRadius: '2px', margin: '10px 0', overflow: 'hidden' },
staleFill: { height: '100%', background: '#00ff88', animation: 'staleCountdown 5s linear forwards' },
buttons: { display: 'flex', gap: '8px', flexWrap: 'wrap' },
button: { padding: '6px 12px', background: 'rgba(0,212,255,0.15)', color: '#00d4ff', border: '1px solid rgba(0,212,255,0.4)', borderRadius: '6px', cursor: 'pointer', fontSize: '12px' },
mission: { display: 'flex', justifyContent: 'space-between', gap: '8px', padding: '8px 10px', margin: '6px 0', background: 'rgba(0,212,255,0.06)', borderRadius: '6px' },
muted: { color: '#8892b0' },
form: { display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap', marginTop: '10px' },
input: { flex: '1 1 180px', padding: '7px 10px', background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(0,212,255,0.3)', borderRadius: '6px', color: '#e0e1dd' },
primary: { padding: '7px 14px', background: '#00d4ff', color: '#0a0e27', border: 'none', borderRadius: '6px', fontWeight: 'bold', cursor: 'pointer' },
check: { display: 'flex', alignItems: 'center', gap: '6px', color: '#8892b0' },
logTitle: { margin: '0 0 8px', color: '#64ffda', fontSize: '14px' },
logRow: { display: 'flex', gap: '8px', padding: '2px 0', fontSize: '12px' },
logTime: { color: '#8892b0', width: '48px', flexShrink: 0, textAlign: 'right' },
};Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is required in the useQuery configuration?
2. What is an optimistic update in the context of useMutation?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the elements of a useMutation call in React Query from left to right:
- Vertical ordering
Order the query lifecycle in TanStack Query v5, from mounting the component to a background refetch: