React
Beginner
1 min read
TanStack Query: Caching and Background Refetching
Example
// npm install @tanstack/react-query
import {
QueryClient, QueryClientProvider,
useQuery, useMutation, useQueryClient,
} from '@tanstack/react-query';
const queryClient = new QueryClient();
// ── Wrap the app ───────────────────────────────────────────────────────────
export function App() {
return (
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
);
}
// ── Fetch todos ────────────────────────────────────────────────────────────
async function fetchTodos() {
const res = await fetch('/api/todos');
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
}
async function addTodo(title) {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, completed: false }),
});
if (!res.ok) throw new Error('Failed to add');
return res.json();
}
function Todos() {
const qc = useQueryClient();
const { data: todos = [], isLoading, isError } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
});
const mutation = useMutation({
mutationFn: addTodo,
onSuccess: () => qc.invalidateQueries({ queryKey: ['todos'] }),
});
if (isLoading) return <p>Loading…</p>;
if (isError) return <p>Something went wrong.</p>;
return (
<div>
<button onClick={() => mutation.mutate('New todo')}>Add Todo</button>
<ul>
{todos.map(t => <li key={t.id}>{t.title}</li>)}
</ul>
</div>
);
}