Open History to see the last commit
1---
2id: prefetching
3title: Prefetching
4---
5β
6If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, you can use the `prefetchQuery` method to prefetch the results of a query to be placed into the cache:
7β
8```tsx
9const prefetchTodos = async () => {
10 // The results of this query will be cached like a normal query
11 await queryClient.prefetchQuery(['todos'], fetchTodos)
12}
13```
14β
15- If data for this query is already in the cache and **not invalidated**, the data will not be fetched
16- If a `staleTime` is passed eg. `prefetchQuery('todos', fn, { staleTime: 5000 })` and the data is older than the specified staleTime, the query will be fetched
17- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `cacheTime`.
18β
19## Manually Priming a Query
20β
21Alternatively, if you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the [Query Client's `setQueryData` method](../reference/QueryClient#queryclientsetquerydata) to directly add or update a query's cached result by key.
22β
23```tsx
24queryClient.setQueryData(['todos'], todos)
25```