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

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

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
Answers to common questions about render props
Kent C. Dodds 🏹 @kentcdodds · 2018-02-12 · via Kent C. Dodds Blog

As I was preparing this article, I was getting ready to give a training to engineers at a local company. They saw my Advanced React Component Patterns course on egghead.io and want to dive deeper into the Render Props pattern. (If you're unfamiliar with the Render Props pattern, I suggest you stop reading now and read "Use a Render Prop" or watch "Never Write Another HoC" (both by the illustrious Michael Jackson), then come back and continue).

In preparing for this training (in addition to creating this), I tweeted this question:

❓ I'm preparing some material about render props in React ⚛️ What are your questions about render props in React? What things are unclear about the pattern? Are there related patterns you'd like to know more about? What kinds of examples could help? 🔁 RT for reach please!

29 199

I got quite a few great responses and for today's newsletter I thought I'd share three of them and simple examples for the answer:

Question 1: Performance?

This is by far the most common question I get whenever talking about Render Props (my tweet had several responses asking about performance). My answer to this question is simple: "That's a really common question. So I'm glad that Ryan Florence answered it in a great blog post! Read "React, Inline Functions, and Performance". "In summary" (to quote the article:

  • Write your code naturally, code to the design.
  • Measure your interactions to find slow paths. Here's how.
  • Use PureComponent and shouldComponentUpdate only when you need to, skipping prop functions (unless they are used in lifecycle hooks for side-effects).

If you really believe that premature optimization is bad practice, then you won't need proof that inline functions are fast, you need proof that they are slow.

I should add one thing. If you're really concerned about inlining your render prop function and perf implications of that, then don't inline the function! :)

class MyComp extends React.Component {
	renderDownshift = (downshift) => <div>{/* Your UI stuff here */}</div>
	render() {
		return <Downshift>{this.renderDownshift}</Downshift>
	}
}

Question 2: Messy Render!?

The not-a-link-posting-robot Mark Erikson asked:

Mark Erikson avatar

Mark Erikson @acemarke

@kentcdodds I'd like to see demonstrations of ways to use render props that DON'T involve stuffing the entire logic into nested functions right there in `render()`. In other words, can you still split out the render func logic into smaller functions for readability?

1 12

Mark is correct. Almost every render prop example I've seen also just shows all the logic in the render function. It's normally an implicit return and then one giant expression. I used to be annoyed by giant render functions, but I've warmed up to them as I've realized that the only reason I didn't like them was because I thought they were complex... 🤔 🤓

In any case, because render props are literally just functions that get called with arguments, you can do whatever you like with them. So I made these two examples for Mark. Here's a smaller version of the concept:

function JustARegularFunctionComponent(props) {
	// do whatever you want in here
	return <div>{/* your stuff */}</div>
}

function App() {
	return (
		<div>
			<div>With a totally different component. Thanks React composibility!</div>
			<RenderPropComp
				render={(arg) => <JustARegularFunctionComponent {...arg} />}
			/>
			<hr />
			<div>
				Inline! You don't have to make it an implicit return arrow function 😉
			</div>
			<RenderPropComp
				render={(arg) => {
					// <-- notice the curly brace!
					// do whatever you want in here
					return <div>{/* your stuff */}</div>
				}}
			/>
		</div>
	)
}

Question 3: Lifecycle Hooks?

Another fairly common question is how to get access to the render prop arguments in lifecycle hooks (because your render prop function is called within the context of the render of your component, how do you get it into componentDidMount.

The answer to this is actually sort of hidden in the answer to Mark's question above. Notice that thanks to React's composability, we can create a separate component, and simply forward the arguments to the props of our component. Like this:

class RegularClassComponent extends React.Component {
	componentDidUpdate() {
		// here you are :)
		console.log(this.props.whatever)
	}
	render() {
		return <div>{/* your ui */}</div>
	}
}

function App() {
	return <RenderPropComp render={(arg) => <RegularClassComponent {...arg} />} />
}

My friend Donavon would be sad if I didn't bring up his preferred pattern of Component Injection. With component injection you could do this even more cleanly:

class RegularClassComponent extends React.Component {
	componentDidUpdate() {
		// here you are :)
		console.log(this.props.whatever)
	}
	render() {
		return <div>{/* your ui */}</div>
	}
}

function App() {
	return <CompInjectionComp component={RegularClassComponent} />
}

I'll leave the implementation details as an exercise for the reader... Or you could look at the new library Donavon created as a result of this conversation, which he published on an airplane ✈️ at 30,000 feet!

Conclusion

The render prop pattern is awesome. I'm looking forward to seeing more projects added to Jared Palmer's awesome-react-render-props! What I love about the Render Prop pattern is that it can encapsulate the logic of a component without sacrificing customizability and simplicity in the markup. More awesome to come I think... Good luck! 👍