useQuery: The Basic Data Fetching Hook
What you'll learn: How to fetch data using TanStack Query's useQuery hook and manage loading, error, and success states automatically.
The Core Concept
useQuery is your primary tool for fetching and caching server data. Instead of managing useState, useEffect, loading flags, and error states yourself, useQuery handles all of it. You provide two things: a unique key that identifies your data, and a function that fetches it.
Think of useQuery like a smart librarian. You give it a card catalog number (queryKey) and instructions for finding the book (queryFn). The librarian remembers where books are, knows when they're being fetched, and can tell you if something went wrong—all automatically.
How It Works
const { data, isLoading, error } = useQuery({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetch('/api/todos');
if (!response.ok) throw new Error('Failed to fetch');
return response.json();
}
});
if (isLoading) return <div>Loading todos...</div>;
if (error) return <div>Error: {error.message}</div>;
return <ul>{data.map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>;
The Three Parts
queryKey: An array that uniquely identifies this query (like['todos']or['user', userId])queryFn: An async function that returns your data (usually a fetch call)- Returned state:
data(your result),isLoading(first fetch),error(if failed)
The queryKey is crucial—TanStack Query uses it for caching and refetching. Same key = same cached data across your app.
Key Takeaway: useQuery replaces your manual data-fetching boilerplate with a declarative hook that automatically manages loading states, errors, and caching based on a unique queryKey and fetch function.