tanstack query’s refetch forces a request to run
When using the useQuery hook from tanstack query (formerly react-query), the enabled: false setting is an option that prevents the initial query execution. But what happens when you use it together with refetch()?
Key Summary
enabled: falseprevents the query from running automatically.- However,
refetch()forcibly runs the query manually, so it operates independently ofenabled: false. - Therefore, even with
enabled: false, callingrefetch()triggers an HTTP request.
Example
const { data, refetch } = useQuery(
['myData'],
fetchData,
{
enabled: false,
}
);
// Manually sends a request when some button is clicked
<button onClick={() => refetch()}>Load</button>
Note: How refetch() behaves
refetch()forces the query to run, regardless ofenabled.- Internally, it works similarly to calling
queryClient.fetchQuery().
20250401
Leave a comment