[Refactor] 전역 상태(isAuthenticated) Context API → Zustand Store 전환#393
[Refactor] 전역 상태(isAuthenticated) Context API → Zustand Store 전환#393Chiman2937 merged 6 commits intomainfrom
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Use the checkbox below for a quick retry:
Walkthrough인증 상태 관리를 React Context 기반의 Provider에서 Zustand 스토어 기반으로 마이그레이션합니다. 새로운 Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
📊 Coverage Report
📈 #393을 main에 병합하면 coverage가 Coverage 요약@@ Coverage Diff @@
## main #393 +/- ##
===========================================
+ Coverage 35.58% 35.69% +0.11%
===========================================
Files 264 267 +3
Lines 12116 12136 +20
Branches 467 469 +2
===========================================
+ Hits 4312 4332 +20
Misses 7804 7804 0 영향받은 파일
|
🎨 Storybook Report✅ 변경 사항이 없습니다 모든 Story가 이전 빌드와 동일합니다.
|
🎭 Playwright Report✨ E2E Test가 성공적으로 완료되었습니다. Test 요약 내용을 확인해주세요.
📊 Test Summary
📜 Test Details✅ Passed Tests (3)
|
🚀 PR Preview Report✨ Build가 성공적으로 완료되었습니다. Preview에서 변경사항을 확인하세요.
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/hooks/use-notification/use-notification-get-unread-count/index.ts`:
- Line 5: 훅 useGetNotificationUnreadCount가 이제 명시적 필드 unReadCount를 반환하므로 기존 소비
코드에서 `const { data: unReadCount = 0 }`로 가져오던 부분을 업데이트해야 합니다; 해당 소비자(예:
provider-notification의 destructure)에서 `const { data: unReadCount = 0 }`를 `const
{ unReadCount }`로 바꾸고, 필요하면 기본값 처리(예: undefined -> 0)는 소비자 쪽에서 안전하게 처리하도록 변경하여
필드 이름 정책을 통일하세요.
In `@src/providers/provider-auth/index.tsx`:
- Around line 1-17: Add the "use client" directive at the top of this module so
AuthProvider is explicitly a client component; update the top of the file before
any imports and ensure the module-level directive applies to the AuthProvider
component (which uses useAuthStore and useEffect) so its intent is explicit and
safe for future independent usage.
ℹ️ Review info
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (12)
package.jsonsrc/components/layout/gnb/index.tsxsrc/components/layout/header/index.tsxsrc/components/pages/auth/login/login-toast-effect/index.tsxsrc/hooks/use-auth/use-auth-login/index.tssrc/hooks/use-auth/use-auth-logout/index.tssrc/hooks/use-notification/use-notification-get-unread-count/index.tssrc/providers/index.tssrc/providers/provider-auth/index.tsxsrc/stores/index.tssrc/stores/useAuthStore/index.tssrc/stores/useNotificationStore/index.ts
| import { API } from '@/api'; | ||
| import { notificationKeys } from '@/lib/query-key/query-key-notification'; | ||
| import { useAuth } from '@/providers'; | ||
| import { useAuthStore } from '@/stores'; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
rg -n --type=ts --type=tsx "useGetNotificationUnreadCount" -C3Repository: WeGo-Together/WeGo_FrontEnd
Length of output: 98
🏁 Script executed:
rg -n "useGetNotificationUnreadCount" -C3Repository: WeGo-Together/WeGo_FrontEnd
Length of output: 2441
🏁 Script executed:
cat -n src/hooks/use-notification/use-notification-get-unread-count/index.tsRepository: WeGo-Together/WeGo_FrontEnd
Length of output: 873
🏁 Script executed:
rg -n "useGetNotificationUnreadCount" --no-filename -B5 -A5 | grep -E "(data|unReadCount|useGetNotificationUnreadCount)" | head -30Repository: WeGo-Together/WeGo_FrontEnd
Length of output: 487
useGetNotificationUnreadCount 훅의 반환 필드 정책 통일 필요
훅이 이제 명시적인 unReadCount 필드를 제공하므로, 기존 data 필드를 사용하던 소비자는 새로운 필드로 업데이트해야 합니다. src/providers/provider-notification/index.tsx 라인 24에서 const { data: unReadCount = 0 }를 const { unReadCount }로 변경해 주세요.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/hooks/use-notification/use-notification-get-unread-count/index.ts` at
line 5, 훅 useGetNotificationUnreadCount가 이제 명시적 필드 unReadCount를 반환하므로 기존 소비 코드에서
`const { data: unReadCount = 0 }`로 가져오던 부분을 업데이트해야 합니다; 해당 소비자(예:
provider-notification의 destructure)에서 `const { data: unReadCount = 0 }`를 `const
{ unReadCount }`로 바꾸고, 필요하면 기본값 처리(예: undefined -> 0)는 소비자 쪽에서 안전하게 처리하도록 변경하여
필드 이름 정책을 통일하세요.
There was a problem hiding this comment.
unReadCount는 React Query로만 관리하고, 전역상태에 저장하지 않을 예정입니다.
사용되는 컴포넌트 마다 api를 호출하는 형태이지만, 캐시된 데이터를 호출하기 때문에 문제가 없습니다.
주요 포인트는 "서버상태는 React Query 로만 관리한다" 입니다.
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check the consumer code in provider-notification to see if it needs updating
cat -n src/providers/provider-notification/index.tsx | grep -A5 -B5 "useGetNotificationUnreadCount"
Length of output: 772
@Chiman2937, 설명 감사합니다! React Query로 서버 상태를 관리하는 아키텍처 결정에 동의합니다. 이는 서버 상태와 클라이언트 상태를 명확하게 분리하는 좋은 패턴입니다.
제 코멘트는 unReadCount를 Zustand로 옮기자는 의도가 아니었고, 단순히 필드명 일관성에 관한 것이었습니다. 현재 훅이 명시적으로 unReadCount 필드를 반환하는데, provider-notification/index.tsx의 24번째 라인에서 여전히 const { data: unReadCount = 0 }로 사용하고 있어서요. const { unReadCount }로 변경하면 훅의 의도가 더 명확해집니다.
다만 큰 이슈는 아니므로, 팀의 판단에 맡기겠습니다. 아키텍처 원칙 잘 이해했습니다! 👍
✏️ Learnings added
Learnt from: Chiman2937
Repo: WeGo-Together/WeGo_FrontEnd PR: 393
File: src/hooks/use-notification/use-notification-get-unread-count/index.ts:5-5
Timestamp: 2026-02-24T05:52:50.560Z
Learning: In WeGo_FrontEnd repository: Server state (e.g., unReadCount from API) should be managed only by React Query, not stored in Zustand global state. Each component calls the API but uses cached data from React Query. Principle: "서버상태는 React Query 로만 관리한다" (Server state managed only by React Query).
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
There was a problem hiding this comment.
그 부분은 명확하게 이해하고 있고, 해당 부분 자체가 삭제될 예정이기 때문에 말씀드렸습니다
There was a problem hiding this comment.
@Chiman2937, 알겠습니다! 해당 코드가 후속 PR에서 삭제될 예정이라면 지금 수정할 필요가 없네요. 말씀해주셔서 감사합니다. 👍
🧠 Learnings used
Learnt from: Chiman2937
Repo: WeGo-Together/WeGo_FrontEnd PR: 393
File: src/hooks/use-notification/use-notification-get-unread-count/index.ts:5-5
Timestamp: 2026-02-24T05:52:50.560Z
Learning: In the WeGo_FrontEnd repository, server state (e.g., unread counts from APIs) must be managed exclusively by React Query and not stored in Zustand or other client state. Components may call the API but should rely on React Query's cache for rendering. Apply this guideline to all hook implementations that deal with server state; avoid writing server-state data to Zustand and prefer React Query data selectors or hooks to access cached results.
📝 변경 사항
Zustand Store 도입 변경사항
커밋 히스토리
7548ad2885fd63fdf1e4a6d34e3c0e4c4f51. Zustand 도입 및 Store 생성
zustand@5.0.11설치 후, 기존 Context API로 관리하던 클라이언트 전역 상태를 Zustand Store로 전환.상태 관리 원칙
isAuthenticated,hasNewNotificationunReadCount, 유저 정보, 모임 목록 등신규 디렉토리 구조
useAuthStore
useNotificationStore
2. AuthProvider - Context → Zustand 전환
src/providers/provider-auth/index.tsx에서 Context API 기반 상태 관리를 완전히 제거하고, Zustand store의 초기값만 설정하는 역할로 변경.Before - Context API 기반
After - Zustand store 초기값 설정만 담당
삭제된 항목
AuthContext(createContext)AuthContextType인터페이스useAuth훅 (Context 기반)useState기반 상태 관리AuthContext.Providerwrapper3. 컴포넌트/훅 import 경로 변경
기존
useAuth(Context) →useAuthStore(Zustand)로 모든 참조를 변경.components/layout/gnb/index.tsxuseAuthfrom@/providersuseAuthStorefrom@/storescomponents/layout/header/index.tsxuseAuthfrom@/providersuseAuthStorefrom@/storescomponents/pages/auth/login/login-toast-effect/index.tsxuseAuthfrom@/providersuseAuthStorefrom@/storeshooks/use-auth/use-auth-login/index.tsuseAuthfrom@/providersuseAuthStorefrom@/storeshooks/use-auth/use-auth-logout/index.tsuseAuthfrom@/providersuseAuthStorefrom@/storeshooks/use-notification/use-notification-get-unread-count/index.tsuseAuthfrom@/providersuseAuthStorefrom@/stores사용 방식은 동일하게 유지:
4. providers/index.ts re-export 정리
useAuth가 삭제되었으므로providers/index.ts에서 해당 export 제거.5. useGetNotificationUnreadCount 반환값 변경
src/hooks/use-notification/use-notification-get-unread-count/index.ts에서useAuth→useAuthStore로 변경하고, 반환값의 프로퍼티명을data→unReadCount로 변경.추가 발견사항
1. useNotificationStore는 후속 PR에서 적용 예정
useNotificationStore가 생성되었으나, 기존NotificationProvider의 Context를 대체하는 작업은 후속 PR에서 진행 예정. 전환 시unReadCount는 서버 상태이므로 store에 포함하지 않고 React Query에서만 관리하며, 클라이언트 상태(receivedData,hasNewNotification)만 store로 이관.변경된 파일 목록
package.jsonpnpm-lock.yamlsrc/stores/index.tssrc/stores/useAuthStore/index.tssrc/stores/useNotificationStore/index.tssrc/providers/provider-auth/index.tsxsrc/providers/index.tssrc/components/layout/gnb/index.tsxsrc/components/layout/header/index.tsxsrc/components/pages/auth/login/login-toast-effect/index.tsxsrc/hooks/use-auth/use-auth-login/index.tssrc/hooks/use-auth/use-auth-logout/index.tssrc/hooks/use-notification/use-notification-get-unread-count/index.ts🔗 관련 이슈
Closes #
🧪 테스트 방법
📸 스크린샷 (선택)
📋 체크리스트
💬 추가 코멘트
CodeRabbit Review는 자동으로 실행되지 않습니다.
Review를 실행하려면 comment에 아래와 같이 작성해주세요
Summary by CodeRabbit