TanStack Query를 사용할 때는 Query Key 관리를 강조하는 경우가 많았다.
공식문서의 링크에 Query Key factories 패턴을 소개하고 있다.
https://tkdodo.eu/blog/effective-react-query-keys
Effective React Query Keys
Learn how to structure React Query Keys effectively as your App grows
tkdodo.eu
const todoKeys = {
all: ['todos'] as const,
lists: () => [...todoKeys.all, 'list'] as const,
list: (filters: string) => [...todoKeys.lists(), { filters }] as const,
details: () => [...todoKeys.all, 'detail'] as const,
detail: (id: number) => [...todoKeys.details(), id] as const,
}
// 🕺 remove everything related
// to the todos feature
// todo 도메인 아래 캐시를 아예 삭제해버리는 것
// 유저 로그아웃 등 stale 여부 상관없이 도메인 초기화 시 사용
// invalidate와 다르게 재요청하지 않음
queryClient.removeQueries({
queryKey: todoKeys.all
})
// 🚀 invalidate all the lists
// todo의 목록 계층(list)만 강제로 stale 처리
// todo 하나 추가/수정/삭제처럼 목록만 갱신하면 되는 상황에서 사용
// 다음 render에서 자동 refetch 발생, 즉 결국 알아서 렌더링됨
queryClient.invalidateQueries({
queryKey: todoKeys.lists()
})
// 🙌 prefetch a single todo
// 미리 데이터를 불러와 캐시에 저장해놓는 것 (선행 fetch)
// 유저가 상세 페이지로 이동하기 직전
// fetch만 하고 UI를 리렌더링하지 않음
queryClient.prefetchQueries({
queryKey: todoKeys.detail(id),
queryFn: () => fetchTodo(id),
})
Query Key factories 패턴을 사용해 도메인 별로 쿼리 키를 관리한다면 협업 시에도 쿼리 키가 중복되는 일 없이 효율적으로 개발할 수 있을 것이다. (디렉토리 구조 예시는 아래처럼)
src/
queries/
user/
userKeys.ts
useUser.ts
useUpdateUser.ts
scenario/
scenarioKeys.ts
useGetScenario.ts
useDeleteScenario.ts'IT > React & Next.js' 카테고리의 다른 글
| [React] 훅 안에서 정의한 함수의 클로저 문제 (0) | 2025.10.28 |
|---|---|
| [Infra] Biome.js VSCode 세팅 (1) | 2025.08.31 |
| [React/TypeScript] React-Spilt-Table 오픈소스 라이브러리 (1) | 2025.04.21 |
| [Next.js] RCC, RSC 활용 예시 (0) | 2025.03.03 |
| [Next.js] SSR에서의 Streaming HTML (0) | 2025.02.24 |