react query how to disable fetch on new instances

Viewed 53

I'm using react query, and I see (from the docs and from trying) that react query refetches on every new instance of useQuery. If I don't want this feature, how can I disable it?

1 Answers

you can use enabled is false then The query will not automatically refetch in the background when new instances mount or new instances appear

this is react query example

     function Todos() {
2   const {
3     isIdle,
4     isLoading,
5     isError,
6     data,
7     error,
8     refetch,
9     isFetching,
10   } = useQuery('todos', fetchTodoList, {
11     enabled: false,
12   })
13 
14   return (
15     <>
16       <button onClick={() => refetch()}>Fetch Todos</button>
17 
18       {isIdle ? (
19         'Not ready...'
20       ) : isLoading ? (
21         <span>Loading...</span>
22       ) : isError ? (
23         <span>Error: {error.message}</span>
24       ) : (
25         <>
26           <ul>
27             {data.map(todo => (
28               <li key={todo.id}>{todo.title}</li>
29             ))}
30           </ul>
31           <div>{isFetching ? 'Fetching...' : null}</div>
32         </>
33       )}
34     </>
35   )
36 }

you just need to write some if conditions for enable to don't refatch in new instances that appear in your condition

Related