Create a QueryClient and useQuery
Keep remote records separate from local interaction state
TanStack Query is a third-party library for reading, caching and updating asynchronous data. A server-owned record may change outside your component; your cache is a local copy, not the authority. Input text, an open dialog and a selected filter can stay in React state. Chapter 23 implemented request lifecycle handling manually. Here a QueryClient manages the cache and observers subscribe through Hooks. The fixtures target documented v5 interfaces of @tanstack/react-query in a reviewed React/Vite project from Chapter 3. Exact dependency versions and browser execution remain pending; each code block is a separate App.jsx. All records are fictional and no network is used.
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function Panel() { const query = useQuery({queryKey:['equipment'],queryFn:async () => ['Tripod','Recorder']}); if (query.isPending) return <p role="status">Loading equipment…</p>; if (query.isError) return <p role="alert">Equipment unavailable.</p>; return <ul>{query.data.map(name => <li key={name}>{name}</li>)}</ul>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Expected after success: Tripod and Recorder. The asynchronous function returns an array; a thrown error or rejected promise is a failure. Do not return undefined as a successful query result. QueryClientProvider supplies the same client to its descendants; creating a new client on every render would discard cache continuity. The lazy state initializer keeps the committed client stable across ordinary renders. The provider owns it for this app lifetime, not a global singleton shared with unrelated users.
Distinguish data status from request activity
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function Panel() { const query = useQuery({queryKey:['stock'],queryFn:async () => ['Tripod']}); return <section><h2>Stock</h2> <button type="button" disabled={query.isFetching} onClick={() => query.refetch()}>Refresh</button> <p role="status">{query.fetchStatus === 'paused' ? 'Waiting for connection' : query.isFetching ? 'Checking stock…' : ''}</p> {query.isError && <p role="alert">Could not refresh stock.</p>} {query.data !== undefined ? <p>{query.data.length ? query.data.join(', ') : 'No stock'}</p> : <p>No result yet.</p>} </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}A cached value can remain visible during a background read, even after a refresh fails. In v5, status describes the result (pending, error or success); fetchStatus describes activity (fetching, paused or idle). isPending and isFetching therefore answer different questions. isLoading indicates an initial pending fetch that is actually fetching. Our instant mock may settle before a visible loading frame; do not assert exact paint timing. An empty array is successful data, not a loading marker.
Enable a query only when its required input exists
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function Panel() { const [category,setCategory] = useState(''); const query = useQuery({queryKey:['stock',category],enabled:category !== '',queryFn:async () => category === 'audio' ? ['Recorder'] : ['Tripod']}); return <section><label>Category <select value={category} onChange={e=>setCategory(e.target.value)}><option value="">Choose…</option><option value="audio">Audio</option><option value="photo">Photo</option></select></label> {!category ? <p>Choose a category first.</p> : query.isPending ? <p role="status">{query.isFetching?'Loading…':'Waiting…'}</p> : query.isError ? <p role="alert">Read failed.</p> : <p>{query.data.join(', ')}</p>} </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Before selection the query does not automatically execute; without cache it may be pending while idle. After Audio is selected the expected result is Recorder. The key contains the input because the result depends on it. Do not manually refetch this disabled query with missing input: enabled controls automatic fetching, not every possible call to refetch. These fixtures disable automatic retries and focus refetches to keep the scenarios easy to reason about; production policy depends on the operation.
Practice
Use the first example, change its query function to reject, then return an empty array. Explain how each case differs from a disabled query. Use the checklist to test the actual UI once dependencies are approved.