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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
P
Privacy & Cybersecurity Law Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
S
Security Affairs
Latest news
Latest news
Security Latest
Security Latest
N
News and Events Feed by Topic
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Exploit Database - CXSecurity.com
The Last Watchdog
The Last Watchdog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
博客园_首页
S
Secure Thoughts
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
腾讯CDC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
N
News and Events Feed by Topic
A
Arctic Wolf
MongoDB | Blog
MongoDB | Blog
爱范儿
爱范儿
Project Zero
Project Zero
A
About on SuperTechFans
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Know Your Adversary
Know Your Adversary
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs

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
Migrating to React's New Context API
2018-04-23 · via Kent C. Dodds Blog

With the recent release of React 16.3.0 came an official context API. You can learn more about the why and how behind this API from my previous blog post: "React's ⚛️ new Context API". Because of this significant change, I'm making an update to my advanced component patterns course on egghead.io to use the new API rather than the old one. As I've been working on updating the course, I've been migrating from the old context API to the new one and I thought I'd show you some of those changes!

In my course, I have a section that shows how to write compound components (a trick I learned from Ryan Florence) that use the context API.

Example Usage

Here's the usage example of the Toggle component that exposes a compound components API:

function Usage(props) {
	return (
		<Toggle onToggle={props.onToggle}>
			<Toggle.On>The button is on</Toggle.On>
			<Toggle.Off>The button is off</Toggle.Off>
			<div>
				<Toggle.Button />
			</div>
		</Toggle>
	)
}

The idea behind the compound components pattern is that it allows you to have components that share implicit state with each other. You can actually use React.Children.map to accomplish it for the simple case, but in this case we need context to share any state at any place in the react tree.

The Old Context API

Here's the version of the implementation with the old context API:

const TOGGLE_CONTEXT = '__toggle__'
function ToggleOn({ children }, context) {
	const { on } = context[TOGGLE_CONTEXT]
	return on ? children : null
}
ToggleOn.contextTypes = {
	[TOGGLE_CONTEXT]: PropTypes.object.isRequired,
}
function ToggleOff({ children }, context) {
	const { on } = context[TOGGLE_CONTEXT]
	return on ? null : children
}
ToggleOff.contextTypes = {
	[TOGGLE_CONTEXT]: PropTypes.object.isRequired,
}
function ToggleButton(props, context) {
	const { on, toggle } = context[TOGGLE_CONTEXT]
	return <Switch on={on} onClick={toggle} {...props} />
}
ToggleButton.contextTypes = {
	[TOGGLE_CONTEXT]: PropTypes.object.isRequired,
}
class Toggle extends React.Component {
	static On = ToggleOn
	static Off = ToggleOff
	static Button = ToggleButton
	static defaultProps = { onToggle: () => {} }
	static childContextTypes = {
		[TOGGLE_CONTEXT]: PropTypes.object.isRequired,
	}
	state = { on: false }
	toggle = () =>
		this.setState(
			({ on }) => ({ on: !on }),
			() => this.props.onToggle(this.state.on),
		)
	getChildContext() {
		return {
			[TOGGLE_CONTEXT]: {
				on: this.state.on,
				toggle: this.toggle,
			},
		}
	}
	render() {
		return <div>{this.props.children}</div>
	}
}

With the old API, you had to specify a string for what context your component would provide in getChildContext and childContextTypes and then specify that same string in the consuming components with contextTypes. I never liked this indirection and normally avoided the problem by making a variable like I do above. In addition, having to attach static properties to the consumers so they could accept the context values wasn't my favorite thing to do either.

Another problem with this API is that it didn't allow values to be updated through a shouldComponentUpdate that returned false. So I had an entire other lesson to demonstrate how to work around that issue: "Rerender Descendants Through shouldComponentUpdate" (hat-tip to Michael Jackson and Ryan Florence for react-broadcast).

The New Context API

The new API doesn't have these problems, which is some of the reason I'm so excited about it. Here's my new version of this same exercise:

const ToggleContext = React.createContext({
	on: false,
	toggle: () => {},
})

class Toggle extends React.Component {
	static On = ({ children }) => (
		<ToggleContext.Consumer>
			{({ on }) => (on ? children : null)}
		</ToggleContext.Consumer>
	)
	static Off = ({ children }) => (
		<ToggleContext.Consumer>
			{({ on }) => (on ? null : children)}
		</ToggleContext.Consumer>
	)
	static Button = (props) => (
		<ToggleContext.Consumer>
			{({ on, toggle }) => <Switch on={on} onClick={toggle} {...props} />}
		</ToggleContext.Consumer>
	)
	toggle = () =>
		this.setState(
			({ on }) => ({ on: !on }),
			() => this.props.onToggle(this.state.on),
		)
	state = { on: false, toggle: this.toggle }
	render() {
		return (
			<ToggleContext.Provider value={this.state}>
				{this.props.children}
			</ToggleContext.Provider>
		)
	}
}

A few things stand out to me in the changes here. As I said, the problems with the old API are gone. Now, rather than the indirection of strings you have explicit components that you must use in order to provide and consume context. You no longer need odd properties to make things work but instead use simple components.

Things are still a tad verbose with those compound components though. Every one of them needs to use the consumer (just like every one of them needed static properties). You can solve that problem (for both APIs) with a render-prop-based Higher Order Component. In this case I wouldn't bother though, it's pretty simple.

The other problem that goes away is updates through shouldComponentUpdate returning false. React's new context API takes care of that for you.

Another thing I love about this is because the consumers are using a render prop API they are highly composable making it possible to do just about anything with them and expose a nice clean API on top because of the dynamic composability of render props (as opposed to the static composability of the old API).

Issues with the New API

One very common pitfall that I'm sure we'll be battling with forever is the importance that the value prop you give to the Provider component is only changed when you want consumers to re-render. This means that doing value={{on: this.state.on, toggle: this.toggle}} in our render method is inadvisable because that creates a new object every time render is called, even if state didn't actually change. Because it's a new object, all the consumers will also be re-rendered.

The impact of this will vary greatly in practice, but in general it's better to provide a value that only changes when state changes (and consumers need to be re-rendered). This is why I say value={this.state}. If you'd prefer not to expose the entire state object to consumers, then you could use this trick I got from Ryan Florence.

One slight issue I have with this is that I have to put the toggle method into state and that feels odd to me, but it's an implementation detail that's not a big deal I think.

Conclusion

After converting a few context using components over to the new API I'm reassured that the React team gave us something brilliant. I love this new API and I'm eager to see how the community embraces it! I hope you enjoy it. Good luck!

P.S. I should note that if you're unable to upgrade to react@16.3.0, you can still use this API via a polyfill: create-react-context.