Please thoroughly read the Important Defaults before reading this guide
This caching example illustrates the story and lifecycle of:
Let's assume we are using the default gcTime
of 5 minutes and the default staleTime
of 0
.
useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
mounts.
['todos']
query key, this query will show a hard loading state and make a network request to fetch the data.['todos']
key.staleTime
(defaults to 0
, or immediately).useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
mounts elsewhere.
['todos']
key from the first query, that data is immediately returned from the cache.fetchTodos
query functions are identical or not, both queries' status
are updated (including isFetching
, isPending
, and other related values) because they have the same query key.['todos']
key is updated with the new data, and both instances are updated with the new data.useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
query are unmounted and no longer in use.
gcTime
to delete and garbage collect the query (defaults to 5 minutes).useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
mounts. The query immediately returns the available cached data while the fetchTodos
function is being run in the background. When it completes successfully, it will populate the cache with fresh data.useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
unmounts.useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
appear within 5 minutes.
['todos']
key is deleted and garbage collected.“This course is the best way to learn how to use React Query in real-world applications.”—Tanner LinsleyCheck it out