React 開發常見的問題是:
「我要把 state 放在哪裡?」
範圍:全域狀態管理(但比 Redux 輕量很多)。
特點:
適合:
function Counter() {
const [count, setCount] = React.useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
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>;
}
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>;
}
判斷以下情境該用哪一種:
中文
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.