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

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

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
React Hooks: What's going to happen to render props?
2018-12-10 · via Kent C. Dodds Blog

About a year ago, I published "How to give rendering control to users with prop getters". In that post, I show the entire implementation (at the time) of react-toggled which I actually built for the sole purpose of teaching some of the patterns that I used in downshift. It's a much smaller and simpler component that implements many of the same patterns as downshift so it served as a great way to teach the prop getters pattern.

Both react-toggled and downshift use the render prop pattern as a mechanism for React component logic code sharing. As I explained in my blog post "When to NOT use Render Props", that's the primary use case for the render prop pattern. But that's also the primary use case for React Hooks as well. And React Hooks are WAY simpler than class components + render props.

So does that mean that when React Hooks are stable you wont need render props at all anymore? No! I can think of two scenarios where the render prop pattern will still be very useful, and I'll share those with you in a moment. But let's go ahead and establish my claim that hooks are simpler by comparing the current version of react-toggled with a hooks-based implementation.

If you're interested, here's the current source for react-toggled.

Here's a typical usage of react-toggled:

function App() {
	return (
		<Toggle>
			{({ on, toggle }) => (
				<button onClick={toggle}>{on ? 'on' : 'off'}</button>
			)}
		</Toggle>
	)
}

If all we wanted was simple toggle functionality, our hook version would be:

function useToggle(initialOn = false) {
	const [on, setOn] = useState(initialOn)
	const toggle = () => setOn(!on)
	return { on, toggle }
}

Then people could use that like so:

function App() {
	const { on, toggle } = useToggle()
	return <button onClick={toggle}>{on ? 'on' : 'off'}</button>
}

Cool! A lot simpler! But the Toggle component in react-toggled actually supports a lot more. For one thing, it provides a helper called getTogglerProps which will give you the correct props you need for a toggler to work (including ariaattributes for accessibility). So let's make that work:

// returns a function which calls all the given functions
const callAll =
	(...fns) =>
	(...args) =>
		fns.forEach((fn) => fn && fn(...args))

function useToggle(initialOn = false) {
	const [on, setOn] = useState(initialOn)
	const toggle = () => setOn(!on)
	const getTogglerProps = (props = {}) => ({
		'aria-expanded': on,
		tabIndex: 0,
		...props,
		onClick: callAll(props.onClick, toggle),
	})
	return {
		on,
		toggle,
		getTogglerProps,
	}
}

And now our useToggle hook can use the getTogglerProps:

function App() {
	const { on, getTogglerProps } = useToggle()
	return <button {...getTogglerProps()}>{on ? 'on' : 'off'}</button>
}

And it's more accessible and stuff. Neat right? Well, what if I don't need the getTogglerProps for my use case? Let's split this up a bit:

// returns a function which calls all the given functions
const callAll =
	(...fns) =>
	(...args) =>
		fns.forEach((fn) => fn && fn(...args))

function useToggle(initialOn = false) {
	const [on, setOn] = useState(initialOn)
	const toggle = () => setOn(!on)
	return { on, toggle }
}

function useToggleWithPropGetter(initialOn) {
	const { on, toggle } = useToggle(initialOn)
	const getTogglerProps = (props = {}) => ({
		'aria-expanded': on,
		tabIndex: 0,
		...props,
		onClick: callAll(props.onClick, toggle),
	})
	return { on, toggle, getTogglerProps }
}

And we could do the same thing to support the getInputTogglerProps and getElementTogglerProps helpers that react-toggled currently supports. This would actually allow us to easily tree-shake out those extra utilities that our app is not using, something that would be pretty unergonomic to do with a render props solution (not impossible, just kinda ugly).

But Kent! I don't want to go and refactor all the places in my app that use the render prop API to use the new hooks API!!

Never fear! Check this out:

const Toggle = ({ children, ...props }) => children(useToggle(props))

There's your render prop component. You can use that just like you were using the old one and migrate over time. In fact, this is how I recommend testing custom hooks!

There's a little more to this (like how do we port the control props pattern to react hooks for example). I'm going to leave that to you to discover. Once you've tried it out for a little bit, then watch me do it. There's a catch with the way we've been testing things a bit that change slightly with hooks (thanks to JavaScript closures).

The remaining use case for render props

Ok, so we can refactor our components to use hooks, and even continue to export react components with a render prop-based API (you might be interested, you may even consider going all out with the hydra pattern). But let's imagine we're now in a future where we don't need render props for logic reuse and everyone's using hooks. Is there any reason to continue writing or using components that expose a render props API?

YES! Observe! Here's an example of using downshift with react-virtualized. Here's the relevant bit:

<List
	// ... some props
	rowRenderer={({ key, index, style }) => (
		<div
		// ... some props
		/>
	)}
/>

Checkout that rowRenderer prop there. Do you know what that is? IT'S A RENDER PROP! What!? 🙀 That's inversion of control in all its glory with render props right there. That's a prop that react-virtualized uses to delegate control of rendering rows in a list to you the user of the component. If react-virtualized were to be rewritten to use hooks, maybe it could accept the rowRenderer as an argument to the useVirtualized hook, but I don't really see any benefit to that over it's current API. So I think render props (and this style of inversion of control) are here to stay for use cases like this.

Conclusion

I hope you find this interesting and helpful. Remember that React hooks are still in alpha and subject to change. They are also completely opt-in and will not require any breaking changes to React's API. I think that's a great thing. Don't go rewriting your apps! Refactor them (once hooks are stable)!

Good luck!