Dependent or conditional fetching
A query needs an identifier, token, or form input before its first request.
TanStack · Pipe
The enabled option controls whether a query runs automatically. Set it to false to defer fetching, then use refetch for manual execution when needed.
Set enabled to false, or to a callback-like condition through derived state, when a query must wait before automatically fetching. Disabled queries can still be triggered with refetch, while enabled queries participate in normal mounting, background-refetching, and invalidation behavior.
useQuery({ queryKey, queryFn, enabled: boolean })| Name | Type | Description |
|---|---|---|
enabled | boolean | () => boolean | Boolean or a function returning a boolean that controls whether the query is enabled. |
No standalone return value; useQuery exposes refetch for manual triggering.
import { useQuery } from '@tanstack/react-query'
export function Todos({ userId }: { userId?: string }) {
const query = useQuery({
queryKey: ['todos', userId],
queryFn: () => fetch(`/api/todos?userId=${userId}`).then(r => r.json()),
enabled: Boolean(userId),
})
return <pre>{JSON.stringify(query.data ?? [], null, 2)}</pre>
}The query waits until userId exists, then runs normally.
A query needs an identifier, token, or form input before its first request.
A screen should wait for an explicit user action before requesting data.
A request should remain inactive until application state satisfies a condition.
Set enabled to false to prevent automatic execution. The hook can still expose cached data, and refetch can manually trigger the request.
Follow-up: How does disabled state differ with cached data? With cached data the query starts successful; without it, it starts pending with an idle fetch status.
A disabled query does not fetch on mount, does not background-refetch, and ignores relevant invalidateQueries and refetchQueries calls. This makes it useful when fetching should be controlled explicitly.
Follow-up: How can a query become lazy rather than permanently disabled? Change the condition used for enabled when the required input becomes available.
The documentation recommends enabled: false when manual refetching is needed, because refetch works properly there. skipToken is a typesafe alternative for disabling a TypeScript query, but it does not support that refetch behavior.
Follow-up: When is skipToken preferable? Use it when conditional disabling should preserve type safety and manual refetch is not required.
skipTokenuseQueryrefetchinvalidateQueriesrefetchQueriesDependent Queries