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

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
F
Full Disclosure
Y
Y Combinator Blog
罗磊的独立博客
A
About on SuperTechFans
L
LINUX DO - 热门话题
Project Zero
Project Zero
The Last Watchdog
The Last Watchdog
P
Privacy International News Feed
大猫的无限游戏
大猫的无限游戏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Spread Privacy
Spread Privacy
K
Kaspersky official blog
C
CERT Recently Published Vulnerability Notes
Simon Willison's Weblog
Simon Willison's Weblog
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News and Events Feed by Topic
W
WeLiveSecurity
GbyAI
GbyAI
MyScale Blog
MyScale Blog
G
GRAHAM CLULEY
www.infosecurity-magazine.com
www.infosecurity-magazine.com
U
Unit 42
The Register - Security
The Register - Security
NISL@THU
NISL@THU
T
Tailwind CSS Blog
Hacker News: Ask HN
Hacker News: Ask HN
V
Visual Studio Blog
AI
AI
P
Proofpoint News Feed
Jina AI
Jina AI
有赞技术团队
有赞技术团队
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
V2EX - 技术
V2EX - 技术
M
MIT News - Artificial intelligence
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
小众软件
小众软件
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
O
OpenAI News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Security @ Cisco Blogs
G
Google Developers Blog
V
V2EX
H
Hacker News: Front Page
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 司徒正美
N
News and Events Feed by Topic
V
Vulnerabilities – Threatpost

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
Mixing Component Patterns
2018-05-07 · via Kent C. Dodds Blog

Let's make a component that supports Render Props, Component Injection, Compound Components, the Provider Pattern, and Higher Order Components!

This last week I gave three workshops at Frontend Masters:

If you're a Frontend Masters subscriber you can watch the unedited version of these courses now. Edited courses should be available for these soon.

The Advanced React Patterns course went especially well. I want to take some of the things that I taught in that workshop and share it with you all + take a it a little further than I took it in the course.

I've created a CodeSandbox that I really suggest you spend a solid 10 minutes reading through. I added a TON of comments to the code to walk you through combining all of the following patterns in a single component:

  • Compound Components
  • Render Props
  • Component Injection
  • Provider Pattern
  • Higher Order Components

Here's the implementation without any comments just to spark your interest:

import * as React from 'react'
import { render } from 'react-dom'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { Switch } from './switch'

const callAll =
	(...fns) =>
	(...args) =>
		fns.forEach((fn) => fn && fn(...args))
const ToggleContext = React.createContext({
	on: false,
	toggle: () => {},
	getTogglerProps: (props) => props,
})

class Toggle extends React.Component {
	static Consumer = (props) => (
		<ToggleContext.Consumer {...props}>
			{(state) => Toggle.getUI(props.children, state)}
		</ToggleContext.Consumer>
	)
	static On = ({ children }) => (
		<Toggle.Consumer>{({ on }) => (on ? children : null)}</Toggle.Consumer>
	)
	static Off = ({ children }) => (
		<Toggle.Consumer>{({ on }) => (on ? null : children)}</Toggle.Consumer>
	)
	static Button = (props) => (
		<Toggle.Consumer>
			{({ getTogglerProps }) => <Switch {...getTogglerProps(props)} />}
		</Toggle.Consumer>
	)
	static getUI(children, state) {
		let ui
		if (Array.isArray(children) || React.isValidElement(children)) {
			ui = children
		} else if (children.prototype && children.prototype.isReactComponent) {
			ui = React.createElement(children, state)
		} else if (typeof children === 'function') {
			ui = children(state)
		} else {
			throw new Error('Please use one of the supported APIs for children')
		}
		return ui
	}
	toggle = () =>
		this.setState(
			({ on }) => ({ on: !on }),
			() => this.props.onToggle(this.state.on),
		)
	getTogglerProps = ({ onClick, ...props } = {}) => ({
		onClick: callAll(onClick, this.toggle),
		'aria-pressed': this.state.on,
		...props,
	})
	state = {
		on: false,
		toggle: this.toggle,
		getTogglerProps: this.getTogglerProps,
	}
	render() {
		const { children, ...rest } = this.props
		return (
			<ToggleContext.Provider value={this.state} {...rest}>
				{Toggle.getUI(children, this.state)}
			</ToggleContext.Provider>
		)
	}
}
Toggle.Consumer.displayName = 'Toggle.Consumer'
Toggle.On.displayName = 'Toggle.On'
Toggle.Off.displayName = 'Toggle.Off'
Toggle.Button.displayName = 'Toggle.Button'

function withToggle(Component) {
	function Wrapper(props, ref) {
		return (
			<Toggle.Consumer>
				{(toggleState) => (
					<Component {...props} toggle={toggleState} ref={ref} />
				)}
			</Toggle.Consumer>
		)
	}
	Wrapper.displayName = `withToggle(${Component.displayName || Component.name})`
	const WrapperWithRef = React.forwardRef(Wrapper)
	hoistNonReactStatics(WrapperWithRef, Component)
	return WrapperWithRef
}

export { Toggle, withToggle }

That's pretty much it for the newsletter today actually. I spent a good chunk of time preparing that codesandbox so give it a good solid look!

codesandbox.io/s/534rnk5yyx

The idea isn't necessarily to encourage that every component be implemented like this one, but more to show how you could use these patterns together to make an extremely flexible API for situations where that's useful. If you are going to choose only one pattern, I recommend the render props pattern, because all the other patterns can be implemented on top of this one and it's the simplest from a consumer's point of view.

Enjoy the codesandbox. And good luck!