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

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

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
When to use Control Props or State Reducers
2018-06-11 · via Kent C. Dodds Blog

You've probably used components or elements that implement the control props pattern. For example:

<input value={this.state.inputValue} onChange={this.handleInputChange} />

Read more about the concept of control props in the react docs.

You may not have had much experience with the idea of a state reducer. In contrast to control props, built-in react elements don't support state reducers (though I hear that reason-react does). My library downshift supports a state reducer. Here's an example of using it to prevent the menu from closing after an item is selected:

function stateReducer(state, changes) {
	if (changes.type === Downshift.stateChangeTypes.clickItem) {
		// when the user clicks an item, prevent
		// keep the isOpen to true
		return { ...changes, isOpen: true }
	}
	return changes
}
const ui = (
	<Downshift stateReducer={stateReducer}>
		{() => <div>{/* some ui stuff */}</div>}
	</Downshift>
)

You can learn how to implement these patterns from my Advanced React Component Patterns material.

Both of these patterns help you expose state management to component consumers and while they have significantly different APIs, they allow much of the same capabilities. So today I'd like to answer the question I've gotten many times which is: “When should I expose a state reducer or a control prop?”

Control Props are objectively more powerful because they allow complete control over state from outside the component. Let's take my favorite Toggle component as an example:

class Example extends React.Component {
	state = { on: false, inputValue: 'off' }
	handleToggle = (on) => {
		this.setState({ on, inputValue: on ? 'on' : 'off' })
	}
	handleChange = ({ target: { value } }) => {
		if (value === 'on') {
			this.setState({ on: true })
		} else if (value === 'off') {
			this.setState({ on: false })
		}
		this.setState({ inputValue: value })
	}
	render() {
		const { on } = this.state
		return (
			<div>
				{/*
          here we're using the `value` control prop
          exposed by the <input /> component
        */}
				<input value={this.state.inputValue} onChange={this.handleChange} />
				{/*
          here we're using the `on` control prop
          exposed by the <Toggle /> component.
        */}
				<Toggle on={on} onToggle={this.handleToggle} />
			</div>
		)
	}
}

Here's a rendered version of this component:

gif of the rendered component showing an input and toggle that sync their state

As you can see, I can control the state of the toggle button by changing the text of the input component, and control the state of the input by clicking on the toggle. This is powerful because it allows me to have complete control over the state of these components.

Control props do come with a cost however. They require that the consumer completely manage state themselves which means the consumer must have a class component with state and change handlers to update that state.

State reducers do not have to manage the component's state themselves (though they can manage some of their own state as needed). Here's an example of using a state reducer:

class Example extends React.Component {
	initialState = { timesClicked: 0 }
	state = this.initialState
	handleToggle = (...args) => {
		this.setState(({ timesClicked }) => ({
			timesClicked: timesClicked + 1,
		}))
	}
	handleReset = (...args) => {
		this.setState(this.initialState)
	}
	toggleStateReducer = (state, changes) => {
		if (this.state.timesClicked >= 4) {
			return { ...changes, on: false }
		}
		return changes
	}
	render() {
		const { timesClicked } = this.state
		return (
			<div>
				<Toggle
					stateReducer={this.toggleStateReducer}
					onToggle={this.handleToggle}
					onReset={this.handleReset}
				/>
				{timesClicked > 4 ? (
					<div>
						Whoa, you clicked too much!
						<br />
					</div>
				) : (
					<div>Click count: {timesClicked}</div>
				)}
			</div>
		)
	}
}

And here's a gif of the rendered interaction.

gif of the rendered component showing a toggle, reset button, and counter that's limited to 4 toggles.

Now, you could definitely implement this experience using a control prop, but I would argue that it's a fair bit simpler if you can use the state reducer. The biggest limitation of a state reducer is that it's impossible to set state of the component from outside it's normal setState calls (I couldn't implement the first example using a state reducer).

I hope this is helpful! Feel free to see the implementation and play around with things in this codesandbox.

Good luck!