React 狀態管理文章封面

在 React 開發中,狀態管理始終是核心議題。隨著應用程式複雜度提升,如何有效管理狀態成為開發者必須面對的挑戰。

為什麼需要狀態管理?

當應用程式只有幾個組件時,使用 useState 就足夠了。但當組件層級變深、狀態需要在多個組件間共享時,問題就出現了:

  • Props Drilling:狀態需要透過多層組件傳遞
  • 重複渲染:狀態更新導致不必要的組件重新渲染
  • 狀態同步:多個組件使用相同狀態,需要保持同步

常見的狀態管理方案

1. useState + Context API

最簡單的狀態管理方案,適合中小型應用。

const ThemeContext = createContext();

function App() {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Layout />
    </ThemeContext.Provider>
  );
}

優點

  • 不需要額外套件
  • 學習曲線低
  • 適合簡單的全域狀態

缺點

  • 所有訂閱 Context 的組件都會重新渲染
  • 不適合頻繁更新的狀態

2. Zustand

輕量級狀態管理庫,使用簡單且性能優異。

import create from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

function Counter() {
  const { count, increment } = useStore();
  return <button onClick={increment}>{count}</button>;
}

優點

  • API 簡潔直觀
  • 性能優異,按需訂閱
  • 支援 TypeScript

缺點

  • 社群相對較小
  • 缺少 DevTools 整合

3. Redux Toolkit

企業級應用的首選,功能完整且生態豐富。

import { createSlice, configureStore } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1 },
  },
});

const store = configureStore({
  reducer: { counter: counterSlice.reducer },
});

優點

  • 強大的 DevTools
  • 完整的生態系統
  • 適合大型應用

缺點

  • 學習曲線較陡
  • 需要較多模板代碼

如何選擇?

根據專案規模選擇:

專案規模 推薦方案 原因
小型(< 10 組件) useState + Context 簡單直接
中型(10-50 組件) Zustand 平衡性能與複雜度
大型(> 50 組件) Redux Toolkit 完整功能與工具

最佳實踐

無論選擇哪種方案,都應該遵循這些原則:

  1. 單一數據源:避免狀態散落在各處
  2. 不可變更新:使用不可變的方式更新狀態
  3. 最小化狀態:只儲存必要的狀態
  4. 派生狀態計算:使用 selector 或 computed 避免重複計算

結論

狀態管理沒有銀彈,選擇最適合你專案的方案才是關鍵。從簡單開始,在需要時再引入更複雜的方案,保持代碼的可維護性。