Open History to see the last commit
1---
2id: initial-query-data
3title: Initial Query Data
4---
5β
6There are many ways to supply initial data for a query to the cache before you need it:
7β
8- Declaratively:
9 - Provide `initialData` to a query to prepopulate its cache if empty
10- Imperatively:
11 - [Prefetch the data using `queryClient.query`](./prefetching.md)
12 - [Manually place the data into the cache using `queryClient.setQueryData`](./prefetching.md)
13β
14## Using `initialData` to prepopulate a query
15β
16There may be times when you already have the initial data for a query available in your app and can simply provide it directly to your query. If and when this is the case, you can use the `config.initialData` option to set the initial data for a query and skip the initial loading state!
17β
18> IMPORTANT: `initialData` is persisted to the cache, so it is not recommended to provide placeholder, partial or incomplete data to this option and instead use `placeholderData`
19β
20[//]: # 'Example'
21β
22```tsx
23const result = useQuery({
24 queryKey: ['todos'],
25 queryFn: () => fetch('/todos'),
26 initialData: initialTodos,
27})
28```
29β
30[//]: # 'Example'
31β
32### `staleTime` and `initialDataUpdatedAt`
33β
34By default, `initialData` is treated as totally fresh, as if it were just fetched. This also means that it will affect how it is interpreted by the `staleTime` option.
35β
36- If you configure your query observer with `initialData`, and no `staleTime` (the default `staleTime: 0`), the query will immediately refetch when it mounts:
37β
38 [//]: # 'Example2'
39β
40 ```tsx
41 // Will show initialTodos immediately, but also immediately refetch todos after mount
42 const result = useQuery({
43 queryKey: ['todos'],
44 queryFn: () => fetch('/todos'),
45 initialData: initialTodos,
46 })
47 ```
48β
49 [//]: # 'Example2'
50β
51- If you configure your query observer with `initialData` and a `staleTime` of `1000` ms, the data will be considered fresh for that same amount of time, as if it was just fetched from your query function.
52β
53 [//]: # 'Example3'
54β
55 ```tsx
56 // Show initialTodos immediately, but won't refetch until another interaction event is encountered after 1000 ms
57 const result = useQuery({
58 queryKey: ['todos'],
59 queryFn: () => fetch('/todos'),
60 initialData: initialTodos,
61 staleTime: 1000,
62 })
63 ```
64β
65 [//]: # 'Example3'
66β
67- So what if your `initialData` isn't totally fresh? That leaves us with the last configuration that is actually the most accurate and uses an option called `initialDataUpdatedAt`. This option allows you to pass a numeric JS timestamp in milliseconds of when the initialData itself was last updated, e.g. what `Date.now()` provides. Take note that if you have a unix timestamp, you'll need to convert it to a JS timestamp by multiplying it by `1000`.
68β
69 [//]: # 'Example4'
70β
71 ```tsx
72 // Show initialTodos immediately, but won't refetch until another interaction event is encountered after 1000 ms
73 const result = useQuery({
74 queryKey: ['todos'],
75 queryFn: () => fetch('/todos'),
76 initialData: initialTodos,
77 staleTime: 60 * 1000, // 1 minute
78 // This could be 10 seconds ago or 10 minutes ago
79 initialDataUpdatedAt: initialTodosUpdatedTimestamp, // eg. 1608412420052
80 })
81 ```
82β
83 [//]: # 'Example4'
84β
85 This option allows the staleTime to be used for its original purpose, determining how fresh the data needs to be, while also allowing the data to be refetched on mount if the `initialData` is older than the `staleTime`. In the example above, our data needs to be fresh within 1 minute, and we can hint to the query when the initialData was last updated so the query can decide for itself whether the data needs to be refetched again or not.
86β
87 > If you would rather treat your data as **prefetched data**, we recommend that you use the `query` api to populate the cache beforehand, thus letting you configure your `staleTime` independently from your `initialData`.
88β
89### Initial Data Function
90β
91If the process for accessing a query's initial data is intensive or just not something you want to perform on every render, you can pass a function as the `initialData` value. This function will be executed only once when the query is initialized, saving you precious memory and/or CPU:
92β
93[//]: # 'Example5'
94β
95```tsx
96const result = useQuery({
97 queryKey: ['todos'],
98 queryFn: () => fetch('/todos'),
99 initialData: () => getExpensiveTodos(),
100})
101```
102β
103[//]: # 'Example5'
104β
105### Initial Data from Cache
106β
107In some circumstances, you may be able to provide the initial data for a query from the cached result of another. A good example of this would be searching the cached data from a todos list query for an individual todo item, then using that as the initial data for your individual todo query:
108β
109[//]: # 'Example6'
110β
111```tsx
112const result = useQuery({
113 queryKey: ['todo', todoId],
114 queryFn: () => fetch('/todos'),
115 initialData: () => {
116 // Use a todo from the 'todos' query as the initial data for this todo query
117 return queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId)
118 },
119})
120```
121β
122[//]: # 'Example6'
123β
124### Initial Data from the cache with `initialDataUpdatedAt`
125β
126Getting initial data from the cache means the source query you're using to look up the initial data from is likely old. Instead of using an artificial `staleTime` to keep your query from refetching immediately, it's suggested that you pass the source query's `dataUpdatedAt` to `initialDataUpdatedAt`. This provides the query instance with all the information it needs to determine if and when the query needs to be refetched, regardless of initial data being provided.
127β
128[//]: # 'Example7'
129β
130```tsx
131const result = useQuery({
132 queryKey: ['todos', todoId],
133 queryFn: () => fetch(`/todos/${todoId}`),
134 initialData: () =>
135 queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId),
136 initialDataUpdatedAt: () =>
137 queryClient.getQueryState(['todos'])?.dataUpdatedAt,
138})
139```
140β
141[//]: # 'Example7'
142β
143### Conditional Initial Data from Cache
144β
145If the source query you're using to look up the initial data from is old, you may not want to use the cached data at all and just fetch from the server. To make this decision easier, you can use the `queryClient.getQueryState` method instead to get more information about the source query, including a `state.dataUpdatedAt` timestamp you can use to decide if the query is "fresh" enough for your needs:
146β
147[//]: # 'Example8'
148β
149```tsx
150const result = useQuery({
151 queryKey: ['todo', todoId],
152 queryFn: () => fetch(`/todos/${todoId}`),
153 initialData: () => {
154 // Get the query state
155 const state = queryClient.getQueryState(['todos'])
156β
157 // If the query exists and has data that is no older than 10 seconds...
158 if (state && Date.now() - state.dataUpdatedAt <= 10 * 1000) {
159 // return the individual todo
160 return state.data.find((d) => d.id === todoId)
161 }
162β
163 // Otherwise, return undefined and let it fetch from a hard loading state!
164 },
165})
166```
167β
168[//]: # 'Example8'
169[//]: # 'Materials'
170β
171## Further reading
172β
173For a comparison between `Initial Data` and `Placeholder Data`, see the [article by TkDodo](https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query).
174β
175[//]: # 'Materials'