告別 Redux Boilerplate?輕量級狀態管理器 Zustand 詳解

4 分鐘

1. Redux 的「煩惱」

Redux 毫無疑問是 React 生態中最著名、最強大的狀態管理函式庫。它的單向資料流、時間旅行除錯等特性使其成為大型、複雜應用程式的可靠選擇。但對於許多中小型專案,Redux 的「樣板程式碼」(Boilerplate)卻常常令人頭疼:

  • Actions & Action Creators: 定義大量的 action 類型和建立函式。
  • Reducers: 撰寫龐大的 switch 陳述式來處理不同的 action。
  • Dispatch & Selectors: 在元件中透過 dispatch 派發 action,透過 useSelector 訂閱狀態變化。
  • Context Provider: 需要在應用程式的根部包覆一個 <Provider>

這一切使得新增一個簡單的狀態也需要修改多個檔案,流程繁瑣。

2. Zustand:一股清流

Zustand(德語意為「狀態」)是由 Poimandres(react-three-fiber 的作者)團隊開發的一個輕量級狀態管理函式庫。它的設計哲學就是極簡非侵入式

核心特點:

  • 程式碼量極少: 實作一個功能,Zustand 的程式碼量通常只有 Redux 的一小部分。
  • 基於 Hooks: 它的一切都圍繞一個自訂 Hook 展開,符合現代 React 的開發習慣。
  • 無需 Context Provider: 你不需要在應用程式頂層包覆任何 Provider。Store 獨立於元件樹,可以在任何地方匯入和使用。
  • 上手快: API 極其簡單,幾分鐘就能學會核心用法。

3. 核心用法

Zustand 的使用分為兩步:建立 Store在元件中使用

a. 建立 Store

你可以將 store 定義在任何一個 .js.ts 檔案中。

// src/store.js
import { create } from 'zustand';

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}));

export default useBearStore;

create 函式接收一個回呼,該回呼的參數是 set 函式(類似於 React 的 setState)。你在這裡定義你的狀態和更新狀態的方法。

b. 在元件中使用

在任何元件中,像使用普通 Hook 一樣使用它。

// src/components/BearCounter.jsx
import useBearStore from '../store';

function BearCounter() {
  const bears = useBearStore((state) => state.bears);
  return <h1>{bears} around here ...</h1>;
}

注意,我們透過一個選擇器函式 (state) => state.bears 來訂閱 bears 狀態。這很重要,因為它能確保只有在 bears 狀態變化時,該元件才會重新渲染,避免了不必要的效能開銷。

// src/components/Controls.jsx
import useBearStore from '../store';

function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation);
  return <button onClick={increasePopulation}>one up</button>;
}

取得 action 也同樣簡單。

4. 非同步 Action

Zustand 處理非同步操作也非常自然,你不需要任何像 redux-thunkredux-saga 這樣的中介軟體。

const useAsyncStore = create((set) => ({
  data: null,
  fetchData: async (url) => {
    const response = await fetch(url);
    const data = await response.json();
    set({ data });
  },
}));

結論

Zustand 並非要完全取代 Redux。Redux 在嚴格的規範、可追溯性和龐大的生態系統方面仍然具有優勢。

然而,對於絕大多數 React 應用程式來說,Zustand 提供了一個更簡單、更快速、心智負擔更低的選擇。如果你厭倦了 Redux 的繁文縟節,或者你的下一個專案需要一個輕快、靈活的狀態管理器,那麼 Zustand 絕對是一個值得你嘗試的優秀方案。