← React Course

REACT ADVANCED · 142

Custom Hooks:抽出可重用的 State / Effect 行為

Custom Hook 不是把任何 function 名稱前面加 use。它的價值是封裝一組 React state/effect lifecycle 行為,讓 component 專注描述 UI。

Learning outcomes

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
140shared dependency distribution → context
141non-render mutable / DOM escape hatch → ref
142reusable state/effect behavior → custom hook

Knowledge check / Final challenge

  1. Course Dashboard 用 reducer 管理 remote state。
  2. User identity 透過 context 傳遞。
  3. 搜尋框用 ref focus。
  4. 把 fetch/cancellation 抽成 custom hook。