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
:
- If the query has cached data, then the query will be initialized in the
status === 'success'
orisSuccess
state. - If the query does not have cached data, then the query will start in the
status === 'pending'
andfetchStatus === 'idle'
state. - The query will not automatically fetch on mount.
- The query will not automatically refetch in the background.
- The query will ignore query client
invalidateQueries
andrefetchQueries
calls that would normally result in the query refetching. refetch
returned fromuseQuery
can be used to manually trigger the query to fetch. However, it will not work withskipToken
.
Typescript users may prefer to use skipToken as an alternative to
enabled = false
.
1function Todos() {
2 const { isLoading, isError, data, error, refetch, isFetching } = useQuery({
3 queryKey: ['todos'],
4 queryFn: fetchTodoList,
5 enabled: false,
6 })
7
8 return (
9 <div>
10 <button onClick={() => refetch()}>Fetch Todos</button>
11
12 {data ? (
13 <>
14 <ul>
15 {data.map((todo) => (
16 <li key={todo.id}>{todo.title}</li>
17 ))}
18 </ul>
19 </>
20 ) : isError ? (
21 <span>Error: {error.message}</span>
22 ) : isLoading ? (
23 <span>Loading...</span>
24 ) : (
25 <span>Not ready ...</span>
26 )}
27
28 <div>{isFetching ? 'Fetching...' : null}</div>
29 </div>
30 )
31}
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:
Lazy Queries #
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:
1function Todos() {
2 const [filter, setFilter] = React.useState('')
3
4 const { data } = useQuery({
5 queryKey: ['todos', filter],
6 queryFn: () => fetchTodos(filter),
7 // ⬇️ disabled as long as the filter is empty
8 enabled: !!filter,
9 })
10
11 return (
12 <div>
13 // 🚀 applying the filter will enable and execute the query
14 <FiltersForm onApply={setFilter} />
15 {data && <TodosTable data={data} />}
16 </div>
17 )
18}
isLoading (Previously: 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.
Typesafe disabling of queries using 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
.
1function Todos() {
2 const [filter, setFilter] = React.useState<string | undefined>()
3
4 const { data } = useQuery({
5 queryKey: ['todos', filter],
6 // ⬇️ disabled as long as the filter is undefined or empty
7 queryFn: filter ? () => fetchTodos(filter) : skipToken,
8 })
9
10 return (
11 <div>
12 // 🚀 applying the filter will enable and execute the query
13 <FiltersForm onApply={setFilter} />
14 {data && <TodosTable data={data} />}
15 </div>
16 )
17}