A query's status === 'pending'
state is sufficient enough to show the initial hard-loading state for a query, but sometimes you may want to display an additional indicator that a query is refetching in the background. To do this, queries also supply you with an isFetching
boolean that you can use to show that it's in a fetching state, regardless of the state of the status
variable:
1function Todos() {
2 const {
3 status,
4 data: todos,
5 error,
6 isFetching,
7 } = useQuery({
8 queryKey: ['todos'],
9 queryFn: fetchTodos,
10 })
11
12 return status === 'pending' ? (
13 <span>Loading...</span>
14 ) : status === 'error' ? (
15 <span>Error: {error.message}</span>
16 ) : (
17 <>
18 {isFetching ? <div>Refreshing...</div> : null}
19
20 <div>
21 {todos.map((todo) => (
22 <Todo todo={todo} />
23 ))}
24 </div>
25 </>
26 )
27}
Displaying Global Background Fetching Loading State #
In addition to individual query loading states, if you would like to show a global loading indicator when any queries are fetching (including in the background), you can use the useIsFetching
hook:
1import { useIsFetching } from '@tanstack/react-query'
2
3function GlobalLoadingIndicator() {
4 const isFetching = useIsFetching()
5
6 return isFetching ? (
7 <div>Queries are fetching in the background...</div>
8 ) : null
9}