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[//]: # 'Example'
9β
10```tsx
11const prefetchTodos = async () => {
12 // The results of this query will be cached like a normal query
13 await queryClient.prefetchQuery({
14 queryKey: ['todos'],
15 queryFn: fetchTodos,
16 })
17}
18```
19β
20[//]: # 'Example'
21β
22- If data for this query is already in the cache and **not invalidated**, the data will not be fetched
23- If a `staleTime` is passed eg. `prefetchQuery({queryKey: ['todos'], queryFn: fn, staleTime: 5000 })` and the data is older than the specified staleTime, the query will be fetched
24- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `cacheTime`.
25β
26## Manually Priming a Query
27β
28Alternatively, 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.
29β
30[//]: # 'Example2'
31β
32```tsx
33queryClient.setQueryData(['todos'], todos)
34```
35β
36[//]: # 'Example2'
37β
38[//]: # 'Materials'
39β
40## Further reading
41β
42For a deep-dive on how to get data into your Query Cache before you fetch, have a look at [#17: Seeding the Query Cache](../community/tkdodos-blog#17-seeding-the-query-cache) from the Community Resources.
43β
44[//]: # 'Materials'