본문 바로가기
Sprint_FESI11/Project

useUserStore VS useAuthStore

by Toddler_AD 2025. 10. 27.

✅ 1. 두 스토어의 목적 한 줄 정의

구분 역할 요약
🧩 useAuthStore “이 사용자가 로그인되어 있는가?” — 즉, 인증 상태 관리
👤 useUserStore “로그인된 사용자가 누구인가?” — 즉, 사용자 정보 관리

즉,

AuthStore는 세션·토큰 중심,
UserStore는 프로필·개인정보 중심 입니다.


✅ 2. 두 스토어의 상태 구조 비교

항목 useAuthStore useUserStore
주요 키 token, tokenExpiry, isAuthenticated user, isLoading, error
데이터 성격 인증 자격(credential) 사용자 데이터(user profile)
저장 위치 localStorage (토큰 영속) 메모리(Zustand store)
초기화 시점 로그인/로그아웃, 토큰 만료 로그인 성공 후 fetchMe() 호출
만료 관리 있음 (checkTokenValidity()) 없음 (단순 fetch)
의존 관계 독립적 (서버에서 로그인 처리) AuthStore 토큰 유효 시 작동
예시 데이터 "eyJhbGciOiJIUzI1..." { id: 3, name: '홍길동', email: 'test@...' }

✅ 3. 실제 동작 흐름 예시로 구분해보기

🔹 로그인 시나리오

[LoginForm] → authService.signin(credentials)
          ↓
(1) 서버에서 JWT 토큰 발급
          ↓
(2) useAuthStore.setToken(token, expiry)
          ↓
(3) useUserStore.fetchMe() 실행 → 사용자 정보 요청
          ↓
(4) userStore.user = { id, name, email } 저장

👉 즉,

  • AuthStore가 먼저 “로그인 상태를 만든다.”
  • 그다음 UserStore가 “누가 로그인했는지 정보를 채운다.”

🔹 토큰 만료 or 로그아웃 시

(1) useAuthStore.logout()
      └ localStorage에서 token 제거
      └ 상태: isAuthenticated = false
(2) useUserStore.clear()
      └ 사용자 정보 초기화
      └ 상태: user = null

👉 AuthStore가 “세션 종료”를 담당하고,
👉 UserStore가 “사용자 데이터 제거”를 담당합니다.


✅ 4. Flux 관점에서 본 역할 분리

단계 AuthStore 역할 UserStore 역할
Action 로그인 / 로그아웃 / 토큰 만료 관리 사용자 정보 로드 / 업데이트
Store 인증 상태 저장소 사용자 데이터 저장소
View 로그인 여부에 따른 UI 전환 사용자 이름, 프로필 표시 등
Data Flow Token 기반으로 전역 세션 관리 AuthStore가 유효할 때만 fetchMe 호출

✅ 5. 코드 관점으로 본 관계 (간단 예시)

// AuthProvider.tsx
'use client';
import { useEffect } from 'react';
import { useAuthStore } from '@/stores/useAuthStore';
import { useUserStore } from '@/stores/useUserStore';

export default function AuthProvider({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, checkTokenValidity, logout } = useAuthStore();
  const { user, fetchMe, clear } = useUserStore();

  useEffect(() => {
    // 1️⃣ 토큰 유효성 검사
    const valid = checkTokenValidity();

    if (!valid) {
      // 2️⃣ 인증 만료 → 전역 상태 초기화
      logout(); // AuthStore
      clear();  // UserStore
      return;
    }

    // 3️⃣ 인증 유효 + 사용자 정보 없음 → 서버로부터 내 정보 불러오기
    if (isAuthenticated && !user) {
      fetchMe();
    }
  }, [isAuthenticated, user, fetchMe, checkTokenValidity, logout, clear]);

  return <>{children}</>;
}

🔸 AuthStore는 토큰이 유효한지를 판단하고,
🔸 UserStore는 유효한 토큰을 이용해 서버에서 “me” 정보를 가져옵니다.


✅ 6. 정리표

구분 useAuthStore useUserStore
관리 대상 토큰 / 로그인 세션 사용자 정보 (프로필)
데이터 출처 로그인 API 응답 /auths/user (me API)
영속성 localStorage 저장 메모리 전용 (로그아웃 시 삭제)
주요 기능 로그인, 로그아웃, 만료 관리 사용자 정보 로딩, 수정, 초기화
관계 UserStore의 전제 조건 AuthStore 유효 시 활성
필요 이유 “로그인 상태 유지” “로그인된 사용자 표시 및 정보 관리”

✅ 7. 핵심 요약

  • AuthStore: 로그인 세션의 “열쇠”
  • UserStore: 로그인된 “사람”의 정보
  • 둘은 독립적이지만, AuthStore → UserStore 순서로 의존합니다.
  • 따라서 Auth가 끊어지면(UserStore.clear) 사용자 정보도 반드시 초기화해야 합니다.