在 React 專案裡,有時候會遇到這種情況:
只是一個資料要傳給最底層的子元件,結果中間的好幾層元件都被迫加上 props
,明明它們完全用不到這個資料?
這就是我們今天要聊的主題 —— Prop Drilling。
Prop Drilling 指的是:當一個資料需要傳到深層子元件時,中間所有層級都必須傳遞 props,即使它們並不需要使用這個資料。
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
層層都得傳下去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。
請問以下程式碼會不會出現 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.