본문으로 건너뛰기

쿼리 옵션

queryKeyqueryFn을 서로 가까이 배치한 채 여러 위치에서 공유하는 가장 좋은 방법 중 하나는 queryOptions 헬퍼를 사용하는 것입니다. 런타임에서 이 헬퍼는 전달된 값을 그대로 반환할 뿐이지만, TypeScript와 함께 사용하면 많은 이점이 있습니다. 쿼리에 사용할 수 있는 모든 옵션을 한곳에서 정의할 수 있으며, 모든 옵션에 대한 타입 추론과 타입 안전성도 확보할 수 있습니다.

import { queryOptions } from '@tanstack/react-query'

function groupOptions(id: number) {
return queryOptions({
queryKey: ['groups', id],
queryFn: () => fetchGroups(id),
staleTime: 5 * 1000,
})
}

// usage:

useQuery(groupOptions(1))
useSuspenseQuery(groupOptions(5))
useQueries({
queries: [groupOptions(1), groupOptions(2)],
})
queryClient.query(groupOptions(23))
queryClient.setQueryData(groupOptions(42).queryKey, newGroups)

무한 쿼리에는 별도의 infiniteQueryOptions 헬퍼가 제공됩니다.

컴포넌트 수준에서 일부 옵션을 여전히 재정의할 수 있습니다. 매우 일반적이고 유용한 패턴은 컴포넌트별 select 함수를 만드는 것입니다:

// Type inference still works, so query.data will be the return type of select instead of queryFn

const query = useQuery({
...groupOptions(1),
select: (data) => data.groupName,
})