Manual Refetching with refetch()
You'll learn how to trigger a data refresh on demand, giving users control over when fresh data is fetched.
What is Manual Refetching?
While TanStack Query automatically refetches your data in many situations (window focus, reconnect, intervals), sometimes you need to refetch on demand—like when a user clicks a "Refresh" button or completes an action that should update the displayed data.
The useQuery hook returns a refetch function that lets you programmatically trigger a new fetch request whenever you want.
How It Works
When you call refetch(), TanStack Query:
- Immediately marks the current data as stale
- Executes your query function again
- Updates the cache with the fresh result
- Re-renders components subscribed to that query
Think of it like a vending machine: while it might automatically restock on a schedule (automatic refetch), you can also press a "restock now" button when you know inventory changed (manual refetch).
Basic Usage
function ProductList() {
const { data, isLoading, refetch } = useQuery({
queryKey: ['products'],
queryFn: fetchProducts,
});
return (
<div>
<button onClick={() => refetch()}>
Refresh Products
</button>
{/* Render products... */}
</div>
);
}
The refetch function returns a promise, so you can also handle the result:
const handleRefresh = async () => {
const result = await refetch();
if (result.isSuccess) {
console.log('Fresh data:', result.data);
}
};
Key Takeaway: The refetch() function from useQuery gives you explicit control to fetch fresh data on demand, perfect for user-triggered refresh actions or after mutations that change server state.