狀態管理面試題很容易被問成:
MobX、Redux、Zustand 哪個比較好?
但比較成熟的回答不是直接選一個,而是先問:
這個狀態真的需要全域管理嗎?
先把 state 分類
React App 裡的 state 大致可以分成四種:
| 類型 | 例子 | 適合放哪 |
|---|---|---|
| Local UI state | modal 開關、input 值、tab | component state |
| Server state | API 回來的資料、快取、同步狀態 | TanStack Query / SWR |
| URL state | 搜尋條件、分頁、排序 | query string |
| Global client state | 使用者偏好、購物車、跨頁 filter | Redux / Zustand / MobX |
很多專案的狀態變複雜,不是因為沒選對 library,而是把 server state、URL state、local UI state 全塞進 global store。
面試可以先講這句:
我會先分類 state。不是所有狀態都應該進 Redux 或 Zustand,server state 通常更適合交給 TanStack Query,URL state 應該放 query string,只有跨頁共享且屬於 client 的狀態才考慮 global store。
Redux 是什麼?
Redux 是單向資料流的狀態管理工具。
核心流程:
UI dispatch action
→ reducer 根據 action 產生新 state
→ store 更新
→ UI 重新渲染優點:
- 規範清楚
- DevTools 成熟
- 狀態變化可追蹤
- 適合大型團隊
- 適合需要審計或嚴格流程的狀態
缺點:
- 心智模型比較重
- 小專案可能太正式
- 傳統 Redux 樣板碼多,通常會搭配 Redux Toolkit
MobX 是什麼?
MobX 是響應式狀態管理。
你把資料設成 observable,使用到資料的 UI 會在資料變動時自動更新。
優點:
- 寫法直覺
- 樣板碼少
- 對 model / class-based domain 友善
- 適合編輯器、表單、複雜互動工具
缺點:
- 資料流較隱性
- 大型團隊需要規範
- debug 心智模型和 Redux 不同
面試回答:
MobX 的優點是 reactive 和低樣板碼,開發體驗很好;但因為狀態更新比較隱性,大型團隊需要清楚規範,否則資料流不如 Redux 容易追蹤。
Zustand 是什麼?
Zustand 是輕量的 React 狀態管理 library。
import { create } from "zustand";
type AuthState = {
userId: string | null;
login: (userId: string) => void;
logout: () => void;
};
export const useAuthStore = create<AuthState>((set) => ({
userId: null,
login: (userId) => set({ userId }),
logout: () => set({ userId: null }),
}));使用:
const userId = useAuthStore((state) => state.userId);
const logout = useAuthStore((state) => state.logout);優點:
- API 簡單
- 不需要 Provider
- 樣板碼少
- selector 寫法直覺
- 很適合中小型 App
缺點:
- 架構規範要自己建立
- 超大型專案要額外約束 store 切分
- middleware / DevTools 要依需求配置
MobX vs Redux vs Zustand
| 工具 | 特性 | 適合場景 |
|---|---|---|
| Redux | 規範強、可追蹤、單向資料流 | 大型團隊、狀態變更需要審計 |
| MobX | 響應式、低樣板碼 | 複雜互動工具、資料模型密集 |
| Zustand | 輕量、API 簡潔 | 中小型 App、快速建立 global store |
我的選擇方式:
- 小到中型 React 專案:Zustand
- 團隊大、流程嚴謹、狀態變化要可追蹤:Redux Toolkit
- 編輯器、設計工具、複雜 domain model:MobX
常見追問
Context 可以取代 Redux 嗎?
部分可以,但 Context 主要是 dependency injection,不是完整狀態管理方案。
如果只是 theme、locale、目前登入使用者,Context 很適合。若是高頻更新或複雜狀態流程,Context 可能造成效能與維護問題。
Server state 要不要放 Redux?
通常不建議。
API 資料會牽涉 cache、loading、error、refetch、stale time、retry,TanStack Query 或 SWR 更適合。
Zustand 會不會太自由?
會,所以團隊需要規範 store 切分、selector 寫法、action 命名和 persistence 邏輯。
面試回答模板
我會先把 state 分成 local UI state、server state、URL state 和 global client state。不是所有狀態都需要全域 store。Redux 規範強、可追蹤,適合大型團隊;MobX 是響應式,寫法直覺,適合複雜互動工具;Zustand 輕量簡潔,適合中小型專案。實務上我會先判斷狀態類型,再選工具,而不是一開始就把所有資料放進 Redux 或 Zustand。