← React Course

REACT ADVANCED · 140

Context:解決跨層傳遞,不是把所有 State 塞進 Global

Context 適合讓一棵 component subtree 取得共同 dependency/state;但它不會自動決定 state 應該放哪,也不會讓所有 update 都變有效率。

Learning outcomes

1. Prop drilling 不一定就是問題

App
└─ Page
   └─ Toolbar
      └─ ThemeButton

如果只有一兩層,props 反而最透明。Context 的價值是讓深層 subtree 共享「環境式 dependency」,例如 theme、authenticated user、locale。

2. Provider

const UserContext =
  createContext(null);

function App() {
  return (
    <UserContext.Provider
      value={user}
    >
      <CoursePage />
    </UserContext.Provider>
  );
}

3. Consumer

function UserBadge() {
  const user =
    useContext(
      UserContext
    );

  return (
    <span>
      {user.name}
    </span>
  );
}

4. Context 不是 authorization

Context 裡放 current user 只是 UI state。真正 permission 仍需 server / policy enforce。

5. Mega-context 的風險

{
  user,
  theme,
  courses,
  filters,
  modal,
  notifications,
  editorDraft,
  ...
}

所有責任塞進同一 provider 會讓 ownership 模糊,也讓 unrelated consumers 更容易跟著 update。

Project checkpoint:Course App dependencies

UserContext

current authenticated user / UI identity display。

Course state

仍由 CoursePage reducer 擁有,不因 Context 存在就全部 global。

Knowledge check

  1. Context 真正解的是 ownership 還是 distribution?
  2. 哪些 state 不值得放 global context?
  3. 為什麼 client context 不能當 authorization?
  4. 替 theme/user/course state 分出三個 responsibility boundaries。