iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
Modern Web

30 天掌握 React & Next.js:從基礎到面試筆記系列 第 8

Day 8:React Hook 是什麼?Hook 解決了哪些問題?

  • 分享至 

  • xImage
  •  

在 React 發展的歷史裡,重用邏輯 (logic reuse) 一直是個難題。
Class component 時代,我們常用 HOCRender Props 來抽象邏輯。
但這兩種方式都會遇到 Wrapper HellNested Hell 的問題,程式碼可讀性差、維護不易。

隨著 Function component 與 Hooks 的出現,React 提供了更乾淨的方式來解決這些痛點:
那就是 Custom Hook

什麼是 Custom Hook?

  • Custom Hook 本質上就是一個普通的 JavaScript 函式。
  • 唯一規則:必須以 use 開頭,並且在裡面使用其他 Hook(例如 useStateuseEffect)。
  • 它的目標:抽象出「可重用的邏輯」,讓不同 component 各自呼叫,但不會共用狀態。

Class Component 的痛點

  1. 邏輯分散:同一個功能需要分散在 componentDidMountcomponentDidUpdatecomponentWillUnmount
  2. Wrapper Hell (HOC):HOC 疊加過多,component tree 太深,props 來源難追。
  3. Nested Hell (Render Props):巢狀結構太深,命名容易衝突,可讀性差。
  4. 重用麻煩:相同的邏輯只能複製貼上,或用 HOC / Render Props 包裝,增加維護成本。

Custom Hook 如何解決?

  • 把邏輯集中在一個 hook 裡,不用分散在多個 lifecycle。
  • 組合性強:一個 component 可以同時使用多個 custom hooks。
  • UI 乾淨:不再需要多層 wrapper 或 function nesting。
  • 更直觀:程式碼一眼能看出「UI 長什麼樣,邏輯在哪裡」。

範例比較

Class + HOC

const withAuth = (WrappedComponent) =>
  class extends React.Component {
    state = { user: null };
    componentDidMount() {
      AuthAPI.check().then((u) => this.setState({ user: u }));
    }
    render() {
      return <WrappedComponent {...this.props} user={this.state.user} />;
    }
  };

class Dashboard extends React.Component {
  render() {
    return <h1>Hello {this.props.user?.name}</h1>;
  }
}

export default withAuth(Dashboard);

Function + Custom Hook

function useAuth() {
  const [user, setUser] = React.useState(null);
  React.useEffect(() => {
    AuthAPI.check().then(setUser);
  }, []);
  return user;
}

function Dashboard() {
  const user = useAuth();
  return <h1>Hello {user?.name}</h1>;
}

Custom Hook 更直觀、可讀性更高

面試回答

在 Class component 時代,我們會用 HOC 或 Render Props 來重用邏輯,但這常導致 wrapper hell 或 nested hell,程式碼變得難讀。
Custom Hook 的出現解決了這個問題:它讓我們可以把邏輯抽象成 hook,再在不同 component 裡重用。這樣不但程式碼更簡潔,也讓 UI 結構更乾淨。

面試英文回答

Back in the Class component era, we used HOCs or Render Props to reuse logic.
The problem was they often caused wrapper hell or nested hell, making the code hard to follow.
Custom Hooks solve this by letting us extract logic into hooks and reuse them across components. This keeps the code cleaner and the UI structure much simpler.

總結

  • Class → HOC/Render Props:解決重用,但帶來可讀性與維護問題。
  • Function → Custom Hook:乾淨、直觀、可組合,取代了舊的方式。
  • Custom Hook 是現代 React 開發裡 最佳實踐 的核心之一。

上一篇
Day 7 : 為什麼不要直接修改 state ?
下一篇
Day 9 : 為什麼 Hooks 一定要寫在最上層
系列文
30 天掌握 React & Next.js:從基礎到面試筆記10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言