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

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

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: Compound Components
2019-02-18 · via Kent C. Dodds Blog

A few weeks ago I did a DevTips with Kent livestream where I show you how to refactor the compound components pattern from a class component to a function component with React hooks:

If you're unfamiliar with compound components, then you probably haven't watched my Advanced React Component Patterns course on egghead.io or on Frontend Masters.

The idea is that you have two or more components that work together to accomplish a useful task. Typically one component is the parent, and the other is the child. The objective is to provide a more expressive and flexible API.

Think of it like <select> and <option>:

<select>
	<option value="value1">key1</option>
	<option value="value2">key2</option>
	<option value="value3">key3</option>
</select>

If you were to try and use one without the other it wouldn't work (or make sense). Additionally it's actually a really great API. Let's check out what it would look like if we didn't have a compound components API to work with (remember, this is HTML, not JSX):

<select options="key1:value1;key2:value2;key3:value3"></select>

I'm sure you can think of other ways to express this, but yuck. And how would you express the disabled attribute with this kind of API? It's kinda madness.

So the compound components API gives you a nice way to express relationships between components.

Another important aspect of this is the concept of "implicit state." The <select> element implicitly stores state about the selected option and shares that with it's children so they know how to render themselves based on that state. But that state sharing is implicit because there's nothing in our HTML code that can even access the state (and it doesn't need to anyway).

Alright, let's get a look at a legit React component that exposes a compound component to understand these principles further. Here's an example of the <Menu /> component from Reach UI that exposes a compound components API:

function App() {
	return (
		<Menu>
			<MenuButton>
				Actions <span aria-hidden>▾</span>
			</MenuButton>
			<MenuList>
				<MenuItem onSelect={() => alert('Download')}>Download</MenuItem>
				<MenuItem onSelect={() => alert('Copy')}>Create a Copy</MenuItem>
				<MenuItem onSelect={() => alert('Delete')}>Delete</MenuItem>
			</MenuList>
		</Menu>
	)
}

In this example, the <Menu> establishes some shared implicit state. The <MenuButton>, <MenuList>, and <MenuItem> components each access and/or manipulate that state, and it's all done implicitly. This allows you to have the expressive API you're looking for.

So how is this done? Well, if you watch my course I show you two ways to do it. One with React.cloneElement on the children and the other with React context. (My course will need to be slightly updated to show how to do this with hooks). In this blog post, I'll show you how to create a simple set of compound components using context.

When teaching a new concept, I prefer to use simple examples at first. So we'll use my favorite <Toggle> component example for this.

Here's how our <Toggle> compound components are going to be used:

function App() {
	return (
		<Toggle onToggle={(on) => console.log(on)}>
			<ToggleOn>The button is on</ToggleOn>
			<ToggleOff>The button is off</ToggleOff>
			<ToggleButton />
		</Toggle>
	)
}

Ok, the moment you've all been waiting for, the actual full implementation of compound components with context and hooks:

import * as React from 'react'
// this switch implements a checkbox input and is not relevant for this example
import { Switch } from '../switch'

const ToggleContext = React.createContext()

function useEffectAfterMount(cb, dependencies) {
	const justMounted = React.useRef(true)
	React.useEffect(() => {
		if (!justMounted.current) {
			return cb()
		}
		justMounted.current = false
	}, dependencies)
}

function Toggle(props) {
	const [on, setOn] = React.useState(false)
	const toggle = React.useCallback(() => setOn((oldOn) => !oldOn), [])
	useEffectAfterMount(() => {
		props.onToggle(on)
	}, [on])
	const value = React.useMemo(() => ({ on, toggle }), [on])
	return (
		<ToggleContext.Provider value={value}>
			{props.children}
		</ToggleContext.Provider>
	)
}

function useToggleContext() {
	const context = React.useContext(ToggleContext)
	if (!context) {
		throw new Error(
			`Toggle compound components cannot be rendered outside the Toggle component`,
		)
	}
	return context
}

function ToggleOn({ children }) {
	const { on } = useToggleContext()
	return on ? children : null
}

function ToggleOff({ children }) {
	const { on } = useToggleContext()
	return on ? null : children
}

function ToggleButton(props) {
	const { on, toggle } = useToggleContext()
	return <Switch on={on} onClick={toggle} {...props} />
}

Here's this component in action:

Error embedding https://codesandbox.io/s/9yp5p2z7yr

So the way this works is we create a context with React where we store the state and a mechanism for updating the state. Then the <Toggle> component is responsible for providing that context value to the rest of the react tree.

I'll walkthrough this implementation and explain the particulars in a future update to my Advanced React Component Patterns course. So keep an eye out for that!

I hope that helps you get some ideas of ways you can make your component APIs more expressive and useful. Good luck!

Read also on my blog: "Inversion of Control"