Skip to main content

context vs. RTK

1. 基本定位

  • Context API

    • React 內建工具,用來避免「props drilling」(層層傳遞 props)。

    • 適合 少量、簡單的全域狀態(例如:主題顏色、登入使用者資訊、語系設定)。

    • 不提供複雜的狀態管理功能(像是 middleware、immutable 更新、時間旅行)。

  • Redux Toolkit (RTK)

    • Redux 官方推薦的標準工具,幫助你用更少樣板程式碼(boilerplate)來寫 Redux。

    • 適合 中大型應用,需要明確的狀態流、可預測的更新、除錯工具(Redux DevTools)、middleware(例如 API 請求攔截、log 記錄)。

    • 支援結合 RTK Query 做資料快取與 API 狀態管理。


2. 使用範例

Context API

// ThemeContext.js
import { createContext, useState } from "react";

export const ThemeContext = createContext();

export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}

// 使用
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";

function Button() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Current theme: {theme}
</button>
);
}

很適合單純的「全域設定」。


Redux Toolkit

// store.js
import { configureStore, createSlice } from "@reduxjs/toolkit";

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

export const { increment, decrement } = counterSlice.actions;

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

// 使用
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement } from "./store";

function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();

return (
<>
<button onClick={() => dispatch(decrement())}>-</button>
<span>{count}</span>
<button onClick={() => dispatch(increment())}>+</button>
</>
);
}

適合「複雜邏輯、多模組、跨頁面」的應用。


3. 差異整理

面向Context APIRedux Toolkit (RTK)
定位React 內建的 props 傳遞替代方案官方推薦的 Redux 寫法
複雜度簡單、輕量中高,結構化
適合場景主題、登入狀態、語系中大型專案、複雜邏輯、多 API
性能任何 context 更新會觸發所有消費者重新渲染透過 useSelector,可避免無關組件重渲染
工具支援Redux DevTools、middleware、RTK Query
資料流比較自由,容易混亂嚴格單向流,狀態可追蹤

結論:

  • 如果只是小專案 or 少數全域狀態 → Context 就夠了。

  • 如果是中大型專案,需要 狀態集中管理、可預測、可除錯RTK 比較合適。