If you ever want to disable a query from automatically running, you can use the enabled = false
option. The enabled option also accepts a callback that returns a boolean.
When enabled
is false
:
status === 'success'
or isSuccess
state.status === 'pending'
and fetchStatus === 'idle'
state.invalidateQueries
and refetchQueries
calls that would normally result in the query refetching.refetch
returned from useQuery
can be used to manually trigger the query to fetch. However, it will not work with skipToken
.TypeScript users may prefer to use skipToken as an alternative to
enabled = false
.
function Todos() { const { isLoading, isError, data, error, refetch, isFetching } = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList, enabled: false, })
return ( <div> <button onClick={() => refetch()}>Fetch Todos</button>
{data ? ( <> <ul> {data.map((todo) => ( <li key={todo.id}>{todo.title}</li> ))} </ul> </> ) : isError ? ( <span>Error: {error.message}</span> ) : isLoading ? ( <span>Loading...</span> ) : ( <span>Not ready ...</span> )}
<div>{isFetching ? 'Fetching...' : null}</div> </div> )}
Permanently disabling a query opts out of many great features that TanStack Query has to offer (like background refetches), and it's also not the idiomatic way. It takes you from the declarative approach (defining dependencies when your query should run) into an imperative mode (fetch whenever I click here). It is also not possible to pass parameters to refetch
. Oftentimes, all you want is a lazy query that defers the initial fetch:
The enabled option can not only be used to permanently disable a query, but also to enable / disable it at a later time. A good example would be a filter form where you only want to fire off the first request once the user has entered a filter value:
function Todos() { const [filter, setFilter] = React.useState('')
const { data } = useQuery({ queryKey: ['todos', filter], queryFn: () => fetchTodos(filter), // ⬇️ disabled as long as the filter is empty enabled: !!filter, })
return ( <div> // 🚀 applying the filter will enable and execute the query <FiltersForm onApply={setFilter} /> {data && <TodosTable data={data} />} </div> )}
isInitialLoading
)Lazy queries will be in status: 'pending'
right from the start because pending
means that there is no data yet. This is technically true, however, since we are not currently fetching any data (as the query is not enabled), it also means you likely cannot use this flag to show a loading spinner.
If you are using disabled or lazy queries, you can use the isLoading
flag instead. It's a derived flag that is computed from:
isPending && isFetching
so it will only be true if the query is currently fetching for the first time.
skipToken
If you are using TypeScript, you can use the skipToken
to disable a query. This is useful when you want to disable a query based on a condition, but you still want to keep the query to be type safe.
IMPORTANT:
refetch
fromuseQuery
will not work withskipToken
. Other than that,skipToken
works the same asenabled: false
.
function Todos() { const [filter, setFilter] = React.useState<string | undefined>()
const { data } = useQuery({ queryKey: ['todos', filter], // ⬇️ disabled as long as the filter is undefined or empty queryFn: filter ? () => fetchTodos(filter) : skipToken, })
return ( <div> // 🚀 applying the filter will enable and execute the query <FiltersForm onApply={setFilter} /> {data && <TodosTable data={data} />} </div> )}
“This course is the best way to learn how to use React Query in real-world applications.”—Tanner LinsleyCheck it out