惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode Profile a React App for Performance
Prop Drilling
2018-05-21 · via Kent C. Dodds Blog

The goal of this post is to not only help you understand what prop drilling is (some also refer to it as "threading"), but also when it can be a problem and mechanisms you can use to side-step or avoid it.

What is prop drilling?

Prop drilling (also called "threading") refers to the process you have to go through to get data to parts of the React Component tree. Let's look at a very simple example of a stateful component (yes, it's my favorite component example):

function Toggle() {
	const [on, setOn] = React.useState(false)
	const toggle = () => setOn((o) => !o)
	return (
		<div>
			<div>The button is {on ? 'on' : 'off'}</div>
			<button onClick={toggle}>Toggle</button>
		</div>
	)
}

Let's refactor this into two components now:

function Toggle() {
	const [on, setOn] = React.useState(false)
	const toggle = () => setOn((o) => !o)
	return <Switch on={on} onToggle={toggle} />
}

function Switch({ on, onToggle }) {
	return (
		<div>
			<div>The button is {on ? 'on' : 'off'}</div>
			<button onClick={onToggle}>Toggle</button>
		</div>
	)
}

Simple enough, the Switch needs a reference to the toggle and on state, so we're sending some props there. Let's refactor it once more to add another layer in our component tree:

function Toggle() {
	const [on, setOn] = React.useState(false)
	const toggle = () => setOn((o) => !o)
	return <Switch on={on} onToggle={toggle} />
}

function Switch({ on, onToggle }) {
	return (
		<div>
			<SwitchMessage on={on} />
			<SwitchButton onToggle={onToggle} />
		</div>
	)
}

function SwitchMessage({ on }) {
	return <div>The button is {on ? 'on' : 'off'}</div>
}

function SwitchButton({ onToggle }) {
	return <button onClick={onToggle}>Toggle</button>
}

This is prop drilling. To get the on state and toggle handler to the right places, we have to drill (or thread) props through the Switch component. The Switch component itself doesn't actually need those values to function, but we have to accept and forward those props because its children need them.

Why is prop drilling good?

Did you ever work in an application that used global variables? What about an AngularJS application that leveraged non-isolate $scope inheritance (or the dreaded $rootScope 😱) The reason that the community has largely rejected these methodologies is because it inevitably leads to a very confusing data model for your application. It becomes difficult for anyone to find where data is initialized, where it's updated, and where it's used. Answering the question of "can I modify/delete this code without breaking anything?" is difficult to answer in that kind of a world. And that's the question you should be optimizing for as you code.

One reason we prefer ESModules over global variables is because it allows us to be more explicit about where our values are used, making it much easier to track values and eases the process determining what impact your changes will have on the rest of the application.

Prop drilling at its most basic level is simply explicitly passing values throughout the view of your application. This is great because if you were coming to the Toggle above and decided you want to refactor the on state to be an enum, you'd easily be able to track all places it's used by following the code statically (without having to run it) and make that update. The key here is explicitness over implicitness.

What problems can prop drilling cause?

In our contrived example above, there's absolutely no problem. But as an application grows, you may find yourself drilling through many layers of components. It's not normally a big deal when you write it out initially, but after that code has been worked in for a few weeks, things start to get unwieldy for a few use cases:

  • Refactor the shape of some data (ie: {user: {name: 'Joe West'}} -> {user: {firstName: 'Joe', lastName: 'West'}})
  • Over-forwarding props (passing more props than is necessary) due to (re)moving a component that required some props but they're no longer needed.
  • Under-forwarding props + abusing defaultProps so you're not made aware of missing props (also due to (re)moving a component).
  • Renaming props halfway through (ie <Toggle on={on} /> renders <Switch toggleIsOn={on} />) making keeping track of that in your brain difficult.

There are various other situations where prop drilling can cause some real pain in the process of refactoring especially.

How can we avoid problems with prop drilling?

One of the things that really aggravates problems with prop drilling is breaking out your render method into multiple components unnecessarily. You'll be surprised how simple a big render method can be when you just inline as much as you can. There's no reason to break things out prematurely. Wait until you really need to reuse a block before breaking it out. Then you won't need to pass props anyway!

Fun fact, there's nothing technically stopping you from writing your entire application as a single React Component. It can manage the state of your whole application and you'd have one giant render method... I am not advocating this though... Just something to think about :)

Note: I've written a blog post about this concept called "When to break up a component into multiple components" that you may enjoy.

Another thing you can do to mitigate the effects of prop-drilling is avoid using defaultProps for anything that's a required prop. Using a defaultProp for something that's actually required for the component to function properly is just hiding important errors and making things fail silently. So only use defaultProps for things that are not required.

Keep state as close to where it's relevant as possible. If only one section of your app needs some state, then manage that in the least common parent of those components rather than putting it at the highest level of the app. Learn more about state management from my blog post: Application State Management.

Use React's Context API for things that are truly necessary deep in the react tree. They don't have to be things you need everywhere in the application (you can render a provider anywhere in the app). This can really help avoid some issues with prop drilling. It's been noted that context is kinda taking us back to the days of global variables. The difference is that because of the way the API was designed, you can still statically find the source of the context as well as any consumers with relative ease.

Conclusion

Prop drilling can be a good thing, and it can be a bad thing. Following some good practices as mentioned above, you can use it as a feature to make your application more maintainable. Good luck!