Built-In Loading, Error, and Success States
What you'll learn: How TanStack Query eliminates the need for manual isLoading, error, and data state variables by providing them automatically.
The Manual Approach You've Been Using
Until now, when fetching data in useEffect, you've been writing code like this:
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setIsLoading(true);
fetch('/api/users')
.then(res => res.json())
.then(data => {
setData(data);
setIsLoading(false);
})
.catch(err => {
setError(err);
setIsLoading(false);
});
}, []);
Three pieces of state, manual updates everywhere, easy to forget setting isLoading back to false.
TanStack Query's Automatic State Management
With TanStack Query, you get these flags automatically from the query result:
const { data, isLoading, isError, error, status } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers
});
No useState calls. No manual flag flipping. The library tracks the request lifecycle and updates these values for you.
isLoading:trueduring the initial fetch (no cached data exists yet)isError:trueif the fetch failederror: the actual error object (if any)status: a string ('pending','error','success') for more detailed states
The library handles all state transitions automatically — when the request starts, when it succeeds, when it fails, even when it refetches in the background.
Why This Matters
You can render UI directly based on these flags without worrying about edge cases like forgetting to set loading back to false on error, or mismatched state updates.
Key Takeaway: TanStack Query provides isLoading, isError, error, and status flags out-of-the-box, replacing all the manual state management you've been doing with useState and useEffect.