iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
Modern Web

30 天掌握 React & Next.js:從基礎到面試筆記系列 第 15

Day 15:Context API vs Local State vs Zustand

  • 分享至 

  • xImage
  •  

React 開發常見的問題是:
「我要把 state 放在哪裡?」

  • 一些狀態放在 component 裡(local state)就好。
  • 一些需要跨層級共享,可以用 Context API。
  • 如果要全域管理,可以選擇 Redux 或是選 Zustand

概念解釋

Local State

  • 範圍:只在 component 裡有效。
  • 適合:表單輸入、按鈕 toggle、modal 開關。

Context API

  • 範圍:整個 component tree 共用。
  • 用途:避免 prop drilling。
  • 適合:主題顏色、登入使用者資訊、語系。

Zustand

  • 範圍:全域狀態管理(但比 Redux 輕量很多)。

  • 特點

    • 不需要大量樣板程式碼(action / reducer)。
    • 支援簡單的 hook 語法,直接呼叫 store。
    • DevTools 支援、效能不錯。
  • 適合

    • 中大型應用,需要共享狀態,但不想用複雜的 Redux。
    • 電商購物車、登入狀態、API 快取。

範例程式碼

Local State

function Counter() {
  const [count, setCount] = React.useState(0);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

Context API

const ThemeContext = React.createContext("light");

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function ThemedButton() {
  const theme = React.useContext(ThemeContext);
  return <button className={theme}>Theme: {theme}</button>;
}

Zustand

import create from "zustand";

// 建立 store
const useCounterStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 }))
}));

// 使用 store
function Counter() {
  const { count, increment } = useCounterStore();
  return <button onClick={increment}>Count: {count}</button>;
}

常見誤解

  • Context 可以完全取代 Zustand:Context 適合小規模共享,但不適合高頻率更新的狀態。
  • 所有 state 都要丟到 Zustand:事實上,大部分狀態用 local state 更簡單。

實務應用

  • 小型應用 → local state + Context。
  • 中大型應用 → Zustand(取代 Redux,更簡單)。
  • 原則:能放小就放小,不要一開始就用全域 store

小練習

判斷以下情境該用哪一種:

  1. Dark mode 切換 → Context
  2. 計數器按鈕 → Local state
  3. 電商網站購物車 → Zustand

面試回答

中文

Local state 用在小範圍。
Context 用在跨層級共享設定。
Zustand 適合全域狀態管理,語法簡單,比 Redux 更輕量。

英文

Local state is for simple, isolated UI.
Context is great to share values like theme or user info.
Zustand is a lightweight global store, simpler than Redux, and good for medium to large apps.
My rule: start with local state, use Context for settings, and use Zustand when the app grows.

總結

  • Local state → 簡單、小範圍。
  • Context → 跨層級共享設定。
  • Zustand → 全域狀態管理,比 Redux 輕巧。
  • 原則:能簡單就簡單,必要時才加工具。

上一篇
Day 14:避免 stale closure — 正確使用依賴陣列、functional updater、useRef
下一篇
Day 16:什麼是 Prop Drilling?為什麼它會變成問題?
系列文
30 天掌握 React & Next.js:從基礎到面試筆記19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言