REACT ADVANCED · 142
Custom Hooks:抽出可重用的 State / Effect 行為
Custom Hook 不是把任何 function 名稱前面加 use。它的價值是封裝一組 React state/effect lifecycle 行為,讓 component 專注描述 UI。
Learning outcomes
- 能辨識何時值得抽 custom hook。
- 能設計 hook input/output contract。
- 能把 effect cleanup 封裝在 hook 內。
- 能避免 custom hook 變成巨大 hidden architecture。
1. 從重複行為開始
function useCourseSearch(
query
) {
const [state, setState] =
useState({
status: "idle",
data: [],
error: null
});
useEffect(() => {
// fetch + cancellation
}, [query]);
return state;
}2. Hook input/output 要像 function contract
query→ useCourseSearch{ status, data, error }
Component 不需要知道 AbortController / request id 等內部同步細節。
3. Custom Hook 不共享 state instance
const a =
useCourseSearch("js");
const b =
useCourseSearch("cpp");每次呼叫 Hook 都有自己的 React state/effect instance;「共用程式碼」不等於「共用同一份 state」。
4. Hook 不應隱藏過多責任
若一個 hook 同時管理 auth、routing、courses、notifications、storage、analytics,它只是把 mega-component 換成 mega-hook。
Project checkpoint:Course Dashboard final reusable behavior
function CourseSearchPage() {
const [query, setQuery] =
useState("");
const result =
useCourseSearch(query);
return (
<SearchView
query={query}
onQueryChange={
setQuery
}
result={result}
/>
);
}React Advanced review
| 課 | 真正能力 |
|---|---|
| 139 | 複雜 state transition → reducer |
| 140 | shared dependency distribution → context |
| 141 | non-render mutable / DOM escape hatch → ref |
| 142 | reusable state/effect behavior → custom hook |
Knowledge check / Final challenge
- Course Dashboard 用 reducer 管理 remote state。
- User identity 透過 context 傳遞。
- 搜尋框用 ref focus。
- 把 fetch/cancellation 抽成 custom hook。