Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

placeholder-query-data.md

68 lines1.6 KB

1---
2id: placeholder-query-data
3title: Placeholder Query Data
4ref: docs/framework/react/guides/placeholder-query-data.md
5---
6​
7[//]: # 'ExampleValue'
8​
9```tsx
10function Todos() {
11 const todosQuery = useQuery(() => ({
12 queryKey: ['todos'],
13 queryFn: () => fetch('/todos'),
14 placeholderData: placeholderTodos,
15 }))
17```
18​
19[//]: # 'ExampleValue'
20[//]: # 'Memoization'
21​
22### Placeholder Data Memoization
23​
24If 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:
25​
26```tsx
27function Todos() {
28 const placeholderData = createMemo(() => generateFakeTodos())
29 const todosQuery = useQuery(() => ({
30 queryKey: ['todos'],
31 queryFn: () => fetch('/todos'),
32 placeholderData: placeholderData(),
33 }))
35```
36​
37[//]: # 'Memoization'
38[//]: # 'ExampleFunction'
39​
40```tsx
41const todosQuery = useQuery(() => ({
42 queryKey: ['todos', id],
43 queryFn: () => fetch(`/todos/${id}`),
44 placeholderData: (previousData, previousQuery) => previousData,
45}))
46```
47​
48[//]: # 'ExampleFunction'
49[//]: # 'ExampleCache'
50​
51```tsx
52function BlogPost(props) {
53 const queryClient = useQueryClient()
54 const blogPostQuery = useQuery(() => ({
55 queryKey: ['blogPost', props.blogPostId],
56 queryFn: () => fetch(`/blogPosts/${props.blogPostId}`),
57 placeholderData: () => {
58 // Use the smaller/preview version of the blogPost from the 'blogPosts'
59 // query as the placeholder data for this blogPost query
60 return queryClient
61 .getQueryData(['blogPosts'])
62 ?.find((d) => d.id === props.blogPostId)
63 },
64 }))
66```
67​
68[//]: # 'ExampleCache'