[Step2.3] cactus: TanStack Query 적용하기 - #8
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Free Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
There was a problem hiding this comment.
[배움]
queryKey를 상수로 분리한 게 좋았어요. 여러 곳에서 같은 key를 참조할 때 오타 방지가 되고, 나중에 key 구조를 바꿀 때도 한 곳만 수정하면 되니까요.
한 가지 더 알면 좋을 패턴인데, 프로젝트가 커질수록 Query Key Factory를 많이 쓴다고 합니다.
export const restaurantKeys = {
all: () => ["restaurants"],
detail: (id) => ["restaurants", id],
};지금처럼 배열 상수로 두면 나중에 상세 페이지나 필터 조건이 생겼을 때 key 간의 계층 관계를 표현하기 어려운데, Factory 패턴은 restaurantKeys.all()을 invalidate하면 하위 key(detail 등)가 전부 무효화되는 장점이 있어요. 지금 규모에선 오버엔지니어링일 수 있지만, 최종 프로젝트에 적용해보면 좋을 것 같습니다!
| const { | ||
| data: newRestaurants, | ||
| isLoading, | ||
| error, | ||
| } = useQuery({ | ||
| queryKey: RESTAURANTS_QUERY_KEY, | ||
| queryFn: getRestaurants, | ||
| }); |
There was a problem hiding this comment.
[논의]
useQuery 로직이 컴포넌트 안에 바로 있는데, 커스텀 훅으로 분리하는 방식도 고려해볼 수 있어요. 지금은 한 곳에서만 쓰이니까 큰 문제는 없는데, 나중에 다른 컴포넌트에서 같은 데이터를 써야 할 때 queryKey랑 queryFn을 다시 작성해야 합니다. 훅으로 빼두면 그냥 가져다 쓰면 되고, staleTime이나 select 같은 옵션을 추가할 때도 한 곳만 수정하면 돼서 저는 커스텀 훅으로 분리했습니다.
There was a problem hiding this comment.
동의합니다. 지금은 한 곳에서만 쓰이지만, 훅으로 분리해두면 staleTime, select 같은 옵션을 추가할 때 컴포넌트를 수정하지 않아도 되고, queryKey와 queryFn이 항상 같은 위치에서 관리된다는 점이 명확하네요. 서버 상태 로직은 훅에, UI 처리(onClose, alert)는 컴포넌트에 남기는 방식으로 리팩토링 반영했습니다!
| if (isLoading) return <StatusText>로딩중입니다.</StatusText>; | ||
| if (error) return <StatusText>{error.message}</StatusText>; |
There was a problem hiding this comment.
[배움]
early return 방식을 하면 early return 이후 newRestaurants가 반드시 존재한다는 게 보장돼서 제 코드에서 restaurants ?? [] 같은 방어 코드가 필요 없어진다는 점에서 인상적입니다.
개인 목표 달성 여부
useQuery,useMutation을 직접 마이그레이션하며 TanStack Query의 핵심 동작 방식을 손에 익힌다.