
React Query를 사용하다 보면 여러 API 요청을 관리하게 되는데, 이때 쿼리키를 체계적으로 관리하는 것이 중요합니다. 잘 구조화된 쿼리키는 다음과 같은 이점이 있습니다.
file directory src/app/constant/queryKey/dummy.ts
export const QUERY_KEYS = {
POST: {
LIST: ["post", "list"],
DETAIL: (id: number) => ["post", "detail", id],
CREATE: ["post", "create"],
UPDATE: (id: number) => ["post", "update", id],
DELETE: (id: number) => ["post", "delete", id],
},
COMMENT: {
LIST: (postId: number) => ["comment", "list", postId],
DETAIL: (id: number) => ["comment", "detail", id],
CREATE: ["comment", "create"],
UPDATE: (id: number) => ["comment", "update", id],
DELETE: (id: number) => ["comment", "delete", id],
},
USER: {
LIST: ["user", "list"],
DETAIL: (id: number) => ["user", "detail", id],
PROFILE: ["user", "profile"],
PLANS: {
INDEX: ["plans", "user"],
SCRAP: ["plans", "user", "scrap"],
},
},
} as const;
// 게시글 목록 조회
export const usePostList = (options?: UseQueryOptions<Post[]>) => {
return useQuery({
queryKey: QUERY_KEYS.POST.LIST,
queryFn: () => customFetch<never, Post[]>(`/posts`),
...options,
});
};
// 게시글 상세 조회
export const usePostDetail = (id: number, options?: UseQueryOptions<Post>) => {
return useQuery({
queryKey: QUERY_KEYS.POST.DETAIL(id),
queryFn: () => customFetch<never, Post>(`/posts/${id}`),
...options,
});
};
// 게시글 생성
export const useCreatePost = (options?: UseMutationOptions<Post, Error, Partial<Post>>) => {
return useMutation({
mutationKey: QUERY_KEYS.POST.CREATE,
mutationFn: (data: Partial<Post>) =>
customFetch<Partial<Post>, Post>(`/posts`, {
method: "POST",
data: data,
}),
...options,
});
};
쿼리키 구조화를 통해 캐시 무효화도 더 쉽게 관리할 수 있습니다.
// 게시글 생성 후 목록 캐시 무효화
export const useCreatePost = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (newPost: Omit<Post, "id">) =>
customFetch<Omit<Post, "id">, Post>("/posts", {
method: "POST",
data: newPost,
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: QUERY_KEYS.POST.LIST });
},
});
};
React Query의 쿼리키를 체계적으로 구조화하면 다음과 같은 이점을 얻을 수 있습니다.
이러한 구조화된 쿼리키 관리는 대규모 애플리케이션에서 특히 유용하며, 팀 프로젝트에서도 일관된 코드 스타일을 유지하는 데 도움이 됩니다.