queryKey์ queryFn์ ์ฌ๋ฌ ๊ณณ์์ ๊ณต์ ํ๋ฉด์๋ ๊ด๋ จ ์ฝ๋๋ฅผ ํ ๊ณณ์ ๋ชจ์ ๊ด๋ฆฌํ๋ ๊ฐ์ฅ ์ข์ ๋ฐฉ๋ฒ ์ค ํ๋๋ queryOptions helper๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด๋ค. ๋ฐํ์ ์ ์ด ํฌํผ๋ ์ ๋ฌ๋ฐ์ ์ต์ ๊ฐ์ฒด๋ฅผ ๊ทธ๋๋ก ๋ฐํํ ๋ฟ์ด์ง๋ง, TypeScript์ ํจ๊ป ์ฌ์ฉํ ๋ ์๋ง์ ์ด์ ์ ์ ๊ณตํ๋ค. ์ฟผ๋ฆฌ์ ํ์ํ ๋ชจ๋ ์ต์ ์ ํ ๊ณณ์์ ์ ์ํ ์ ์์ผ๋ฉฐ, ์ด๋ฅผ ํตํด type inference(ํ์ ์ถ๋ก )๊ณผ type safety(ํ์ ์์ ์ฑ)์ ์๋ฒฝํ๊ฒ ๋ณด์ฅ๋ฐ์ ์ ์๋ค.
import { queryOptions } from '@tanstack/react-query'
function groupOptions(id: number) {
return queryOptions({
queryKey: ['groups', id],
queryFn: () => fetchGroups(id),
staleTime: 5 * 1000,
})
}
useQuery(groupOptions(1))
useSuspenseQuery(groupOptions(5))
useQueries({
queries: [groupOptions(1), groupOptions(2)],
})
queryClient.prefetchQuery(groupOptions(23))
queryClient.setQueryData(groupOptions(42).queryKey, newGroups)
๋ฌดํ ์ฟผ๋ฆฌ(Infinite Queries)๋ฅผ ์ํด์๋ ๋ณ๋์ infiniteQueryOptions helper๊ฐ ์ ๊ณต๋๋ค.
์ปดํฌ๋ํธ ๋จ์์ ์ผ๋ถ ์ต์ ์ ์ฌ์ ์ํ ์๋ ์๋ค. ๋งค์ฐ ํํ๊ณ ์ ์ฉํ ํจํด์ ๊ฐ ์ปดํฌ๋ํธ์ ํ์์ ๋ง๊ฒ select ํจ์๋ฅผ ์ถ๊ฐํ๋ ๊ฒ์ด๋ค.
// ํ์
์ถ๋ก ์ ์ฌ์ ํ ๋์ํ๋ค.
// query.data์ ํ์
์ queryFn์ ๋ฐํ ํ์
์ด ์๋๋ผ select ํจ์์ ๋ฐํ ํ์
์ด ๋๋ค.
const query = useQuery({
...groupOptions(1),
select: (data) => data.groupName,
})
https://tanstack.com/query/latest/docs/framework/react/guides/query-options
Query Options | TanStack Query React Docs
One of the best ways to share queryKey and queryFn between multiple places, yet keep them co-located to one another, is to use the queryOptions helper. At runtime, this helper just returns whatever yo...
tanstack.com
'Frontend > TanStack Query' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| Parallel Queries (0) | 2025.11.03 |
|---|---|
| Network Mode (0) | 2025.10.24 |
| Query Functions (0) | 2025.10.22 |
| Query Keys (0) | 2025.10.21 |
| Queries (0) | 2025.10.20 |