> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-1/react-with-typescript/react/5./undefined.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 전역상태관리

## 설계 원칙 (요약)

1. **클라이언트 전역 상태(Store)**: UI·인증 플래그·실시간 알림 큐 등 “클라이언트 로컬 상태”
2. **서버 상태(Server State)**: 리스트/상세/통계 등 API 기반 데이터는 **React Query**로 (캐싱/동기화 자동)
3. **영속성(persist)**: 정말 필요한 최소값만 (예: 테마, API 기본 URL, 로그인 세션 플래그).
   * JWT는 가능하면 **httpOnly 쿠키**(권장). 혹은 **메모리 저장**(+ 리프레시만 쿠키).
4. **보안**: 프론트 권한 체크는 UX용. **서버에서 최종 검사** 필수.
5. **실시간**: WebSocket/SSE 연결 상태는 Store에서 관리, 메시지는 Store로 push.

***

## 전역 상태 구조(예시)

```
store
 ├─ settingsSlice        // #1 앱 설정(기본 URL, 테마, 전역 로딩)
 ├─ authSlice            // #2 인증/인가 (user, roles, isAuthed, tokenState)
 └─ notifySlice          // #3 실시간 알림 (items, unreadCount, connStatus)
```

React Query는 별도 Provider에서 설정.

***

## 1) settingsSlice (기본 URL, UI 로딩, 테마)

* `baseUrl`: axios 인스턴스 변경 시 참조
* `theme`: 'light' | 'dark'
* `globalLoading`: 숫자 카운터(동시 요청 대비)

```ts
// settingsSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

type Theme = 'light' | 'dark';
type SettingsState = {
  baseUrl: string;
  theme: Theme;
  globalLoading: number; // 0 이상이면 전역 로딩 ON
};

const initialState: SettingsState = {
  baseUrl: 'https://api.example.com',
  theme: 'light',
  globalLoading: 0,
};

const settingsSlice = createSlice({
  name: 'settings',
  initialState,
  reducers: {
    setBaseUrl: (s, a: PayloadAction<string>) => { s.baseUrl = a.payload; },
    toggleTheme: (s) => { s.theme = s.theme === 'light' ? 'dark' : 'light'; },
    startLoading: (s) => { s.globalLoading += 1; },
    endLoading: (s) => { s.globalLoading = Math.max(0, s.globalLoading - 1); },
  },
});

export const { setBaseUrl, toggleTheme, startLoading, endLoading } = settingsSlice.actions;
export default settingsSlice.reducer;
```

> persist 대상: `baseUrl`, `theme` (✅), `globalLoading` (❌ 런타임성)

***

## 2) authSlice (JWT, 인증/인가)

* **권장 저장 방식**
  * Access 토큰: **httpOnly 쿠키** → JS 접근 불가(가장 안전)
  * Refresh 토큰: httpOnly 쿠키
  * 클라이언트 Store에는 `isAuthenticated`, `user`, `roles/permissions`만
* 쿠키가 불가하면 **메모리 저장**(앱 재시작 시 재로그인 필요) + 리프레시로 보완
* redux-persist에는 **user/roles만** (민감한 토큰은 저장 X)

```ts
ts복사// authSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

type Role = 'ADMIN' | 'USER';
type User = { id: string; name: string; email: string; roles: Role[] };

type AuthState = {
  isAuthenticated: boolean;
  user: User | null;
  permissions: string[]; // 서버에서 계산된 권한 목록
  // 메모리 토큰 전략을 쓸 경우
  accessToken?: string; // ⚠️ 가능하면 저장하지 말 것 (혹은 메모리 전용 모듈)
};

const initialState: AuthState = {
  isAuthenticated: false,
  user: null,
  permissions: [],
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setSession: (s, a: PayloadAction<{ user: User; permissions: string[] }>) => {
      s.isAuthenticated = true;
      s.user = a.payload.user;
      s.permissions = a.payload.permissions;
    },
    clearSession: (s) => {
      s.isAuthenticated = false;
      s.user = null;
      s.permissions = [];
      delete s.accessToken;
    },
    setAccessTokenInMemory: (s, a: PayloadAction<string | undefined>) => {
      s.accessToken = a.payload;
    },
  },
});

export const { setSession, clearSession, setAccessTokenInMemory } = authSlice.actions;
export default authSlice.reducer;
```

#### axios 인터셉터(요청/응답) 예시

* 전역 로딩 카운터 연동
* 401 → 리프레시 시도 → 실패 시 `clearSession`

```ts
// http.ts
import axios from 'axios';
import { store } from './store';
import { startLoading, endLoading } from './settingsSlice';
import { clearSession } from './authSlice';

export const http = axios.create({ withCredentials: true }); // 쿠키 전송

http.interceptors.request.use((config) => {
  store.dispatch(startLoading());
  // 메모리 토큰 전략일 경우
  const token = store.getState().auth.accessToken;
  if (token) config.headers.Authorization = `Bearer ${token}`;
  // baseUrl은 settings에서
  const baseUrl = store.getState().settings.baseUrl;
  config.baseURL = baseUrl;
  return config;
});

http.interceptors.response.use(
  (res) => {
    store.dispatch(endLoading());
    return res;
  },
  async (err) => {
    store.dispatch(endLoading());
    if (err?.response?.status === 401) {
      try {
        await axios.post('/auth/refresh', {}, { withCredentials: true, baseURL: store.getState().settings.baseUrl });
        return http(err.config); // 재시도
      } catch {
        store.dispatch(clearSession());
      }
    }
    return Promise.reject(err);
  }
);
```

> React Query와 함께 쓸 때는 **데이터 fetching은 useQuery**로, 인증 흐름/세션은 Store로.

***

## 3) 실시간 알림 notifySlice (WebSocket/SSE)

* 연결 상태: `connecting | open | closed | error`
* 알림 큐: 최근 N개 보관, 읽음 처리, 뱃지 카운트

```ts
//notifySlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

type Notify = { id: string; message: string; ts: number; read: boolean };

type NotifyState = {
  connStatus: 'connecting' | 'open' | 'closed' | 'error';
  items: Notify[];
  unreadCount: number;
};

const initialState: NotifyState = {
  connStatus: 'closed',
  items: [],
  unreadCount: 0,
};

const MAX_ITEMS = 100;

const notifySlice = createSlice({
  name: 'notify',
  initialState,
  reducers: {
    setConnStatus: (s, a: PayloadAction<NotifyState['connStatus']>) => { s.connStatus = a.payload; },
    pushNotify: (s, a: PayloadAction<Notify>) => {
      s.items.unshift(a.payload);
      if (!a.payload.read) s.unreadCount += 1;
      if (s.items.length > MAX_ITEMS) s.items.pop();
    },
    markRead: (s, a: PayloadAction<string>) => {
      const n = s.items.find(x => x.id === a.payload);
      if (n && !n.read) { n.read = true; s.unreadCount = Math.max(0, s.unreadCount - 1); }
    },
    markAllRead: (s) => {
      s.items.forEach(n => n.read = true);
      s.unreadCount = 0;
    },
    clearAll: (s) => { s.items = []; s.unreadCount = 0; },
  },
});

export const { setConnStatus, pushNotify, markRead, markAllRead, clearAll } = notifySlice.actions;
export default notifySlice.reducer;
```

#### WebSocket(STOMP) 연결 헬퍼

* 로그인 성공 시 연결, 로그아웃 시 해제
* 재연결 백오프(간단 지수 backoff) 권장

```ts
// useNotifications.ts (간단 예시)
import { useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { setConnStatus, pushNotify } from './notifySlice';

export function useNotifications() {
  const dispatch = useDispatch();
  const isAuthed = useSelector((s: any) => s.auth.isAuthenticated);
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    if (!isAuthed) {
      wsRef.current?.close();
      wsRef.current = null;
      dispatch(setConnStatus('closed'));
      return;
    }
    dispatch(setConnStatus('connecting'));
    const ws = new WebSocket('wss://notify.example.com/ws');
    wsRef.current = ws;

    ws.onopen = () => dispatch(setConnStatus('open'));
    ws.onmessage = (e) => {
      const payload = JSON.parse(e.data);
      // { id, message, ts }
      dispatch(pushNotify({ ...payload, read: false }));
    };
    ws.onerror = () => dispatch(setConnStatus('error'));
    ws.onclose = () => dispatch(setConnStatus('closed'));

    return () => ws.close();
  }, [isAuthed, dispatch]);
}
```

> STOMP/SockJS 사용 시도 동일한 패턴(구독 경로 `/user/queue/notice` 등).

***

## store 구성 & persist

```ts
// store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import settings from './settingsSlice';
import auth from './authSlice';
import notify from './notifySlice';
import storage from 'redux-persist/lib/storage';
import { persistReducer, persistStore } from 'redux-persist';

const rootReducer = combineReducers({ settings, auth, notify });

const persistConfig = {
  key: 'root',
  storage,
  whitelist: ['settings', 'auth'], // notify는 비영속(실시간)
  transforms: [], // 필요 시 민감 데이터 필터/마이그레이션
};

const persisted = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persisted,
  middleware: (gDM) => gDM({ serializableCheck: false }),
});
export const persistor = persistStore(store);
export type RootState = ReturnType<typeof store.getState>;
```

> auth에선 토큰 저장은 피하고 `user/permissions/isAuthenticated` 정도만 보존 권장.

***

## React Query 세팅(서버 상태)

```ts
// query.ts
import { QueryClient } from '@tanstack/react-query';
export const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: 1, refetchOnWindowFocus: false } },
});
```

```tsx
// main.tsx
import { PersistGate } from 'redux-persist/integration/react';
import { Provider } from 'react-redux';
import { QueryClientProvider } from '@tanstack/react-query';
import { store, persistor } from './store';
import { queryClient } from './query';

<Provider store={store}>
  <PersistGate loading={null} persistor={persistor}>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </PersistGate>
</Provider>
```

***

## 라우트/버튼 가드 (인가)

```tsx
// useAuth.ts
import { useSelector } from 'react-redux';
import { RootState } from './store';

export function useAuth() {
  const { isAuthenticated, user, permissions } = useSelector((s: RootState) => s.auth);
  const has = (p: string) => permissions.includes(p);
  const hasAny = (arr: string[]) => arr.some(permissions.includes.bind(permissions));
  return { isAuthenticated, user, has, hasAny };
}

// 예: 버튼
function DeleteButton() {
  const { has } = useAuth();
  return <button disabled={!has('POST_DELETE')}>삭제</button>;
}
```

***

## 체크리스트

* [ ] **설정**: baseUrl·theme persist, globalLoading 카운터
* [ ] **인증/인가**: 세션(`user/permissions`), 401 리프레시, 로그아웃 정리
* [ ] **실시간**: 연결 상태·알림 큐·뱃지 카운트, 읽음 처리
* [ ] **서버 상태 분리**: 목록/상세는 React Query로
* [ ] **보안**: 가능한 httpOnly 쿠키, 프론트 체크는 UX용

## etc

그밖에,&#x20;

웹소켓 사용 실습

배포 실습
