본문 바로가기
IT/React & Next.js

[TanStack Query] Query Key factories로 Query Key 관리하기

by 저당단 2025. 12. 5.

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