iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Modern Web

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

Day 16:什麼是 Prop Drilling?為什麼它會變成問題?

  • 分享至 

  • xImage
  •  

在 React 專案裡,有時候會遇到這種情況:
只是一個資料要傳給最底層的子元件,結果中間的好幾層元件都被迫加上 props,明明它們完全用不到這個資料?

這就是我們今天要聊的主題 —— Prop Drilling

核心概念

Prop Drilling 指的是:當一個資料需要傳到深層子元件時,中間所有層級都必須傳遞 props,即使它們並不需要使用這個資料。

範例程式碼

錯誤示範(典型 Prop Drilling)

function App() {
  const user = { name: "Andy" };
  return <Parent user={user} />;
}

function Parent({ user }) {
  // Parent 根本用不到 user,卻還是要傳
  return <Child user={user} />;
}

function Child({ user }) {
  return <h1>Hello {user.name}</h1>;
}
  • user 最後只在 Child 被用到
  • App → Parent → Child 層層都得傳下去
  • 這就是 prop drilling

正確示範(用 Context API 解決,可以依照需求改用狀態管理)

const UserContext = React.createContext();

function App() {
  const user = { name: "Andy" };
  return (
    <UserContext.Provider value={user}>
      <Parent />
    </UserContext.Provider>
  );
}

function Parent() {
  return <Child />;
}

function Child() {
  const user = React.useContext(UserContext);
  return <h1>Hello {user.name}</h1>;
}

這樣就不需要中間一層一層傳 props。

常見問題與缺點

  • 中間元件變得臃腫
  • 程式碼難以維護
  • 一旦資料結構更動,需要修改很多層

解決方式

  1. Context API → 適合中小型專案
  2. 狀態管理工具(Redux, Zustand, Jotai) → 跨頁面或大型專案
  3. 調整組件結構 → 減少不必要的層級

小練習

請問以下程式碼會不會出現 Prop Drilling?

function App() {
  const theme = "dark";
  return <Header theme={theme} />;
}

function Header({ theme }) {
  return <Navbar theme={theme} />;
}

function Navbar({ theme }) {
  return <Button theme={theme} />;
}

答案:會,因為 theme 只在 Button 用到,但所有元件都必須傳遞它。

面試回答

中文

Prop Drilling 指的是資料必須透過多層元件傳遞,雖然中間元件不需要使用它,卻仍然要加上 props。
這會讓程式碼冗長、難維護。
解決方式包括:

  • 使用 React 的 Context API
  • 或在大型專案中用 Redux / Zustand 等狀態管理工具。

英文

Prop drilling happens when data is passed through many components that don’t actually use it, just to reach a child.
It makes code harder to read and maintain.
To avoid it, we can use the Context API for small cases, or state management libraries like Redux or Zustand in larger apps.

總結

  • Prop Drilling = 不必要的層層傳 props
  • 缺點:程式碼臃腫、難維護
  • 解法:Context API / 狀態管理工具 / 元件結構調整

上一篇
Day 15:Context API vs Local State vs Zustand
下一篇
Day 17 — 什麼是 React.memo
系列文
30 天掌握 React & Next.js:從基礎到面試筆記19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言