Open History to see the last commit
1---
2id: placeholder-query-data
3title: Placeholder Query Data
4---
5β
6## What is placeholder data?
7β
8Placeholder data allows a query to behave as if it already has data, similar to the `initialData` option, but **the data is not persisted to the cache**. This comes in handy for situations where you have enough partial (or fake) data to render the query successfully while the actual data is fetched in the background.
9β
10> Example: An individual blog post query could pull "preview" data from a parent list of blog posts that only include title and a small snippet of the post body. You would not want to persist this partial data to the query result of the individual query, but it is useful for showing the content layout as quickly as possible while the actual query finishes to fetch the entire object.
11β
12There are a few ways to supply placeholder data for a query to the cache before you need it:
13β
14- Declaratively:
15 - Provide `placeholderData` to a query to prepopulate its cache if empty
16- Imperatively:
17 - [Prefetch or fetch the data using `queryClient` and the `placeholderData` option](../guides/prefetching)
18β
19## Placeholder Data as a Value
20β
21```tsx
22function Todos() {
23 const result = useQuery(['todos'], () => fetch('/todos'), {
24 placeholderData: placeholderTodos,
25 })
26}
27```
28β
29### Placeholder Data as a Function
30β
31If the process for accessing a query's placeholder data is intensive or just not something you want to perform on every render, you can memoize the value or pass a memoized function as the `placeholderData` value:
32β
33```tsx
34function Todos() {
35 const placeholderData = useMemo(() => generateFakeTodos(), [])
36 const result = useQuery(['todos'], () => fetch('/todos'), { placeholderData })
37}
38```
39β
40### Placeholder Data from Cache
41β
42In some circumstances, you may be able to provide the placeholder data for a query from the cached result of another. A good example of this would be searching the cached data from a blog post list query for a preview version of the post, then using that as the placeholder data for your individual post query:
43β
44```tsx
45function Todo({ blogPostId }) {
46 const result = useQuery(['blogPost', blogPostId], () => fetch(`/blogPosts/${blogPostId}`), {
47 placeholderData: () => {
48 // Use the smaller/preview version of the blogPost from the 'blogPosts' query as the placeholder data for this blogPost query
49 return queryClient
50 .getQueryData(['blogPosts'])
51 ?.find(d => d.id === blogPostId)
52 },
53 })
54}
55```
56β
57## Further reading
58β
59For a comparison between `Placeholder Data` and `Initial Data`, have a look at the [Community Resources](../community/tkdodos-blog#9-placeholder-and-initial-data-in-react-query).