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

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

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
The state reducer pattern ⚛️ 🏎
2018-02-19 · via Kent C. Dodds Blog

This post is here for historical reasons. Please read an updated version of this blog post with React Hooks! You may also be interested in the more general concept of "Inversion of Control".

This last week, @notruth (new code contributor to the downshift project), filed an issue: "closeOnSelection" property (Multiple selection out of box). All you really need to know about that issue is that the decisions made about how downshift updates its state based on user interaction in certain scenarios didn't agree with what @notruth wants for their implementation. 😖

Why do we use UI libraries?

With UI libraries like downshift, you can offer two things:

  1. The way it works
  2. The way it looks

UI libraries have to make decisions about these things to be useful at all. But the fewer decisions you make, the more generically useful and flexible (lego-block-like) your library can be. However, it's a delicate balance. The more decisions you make, the more useful you can be for some use cases, but you run the risk of becoming too opinionated and totally unusable for other use cases. If you make no decisions at all, then ummm... why am I installing your library? 🤔

For downshift, I decided to not make any decisions about the way it looks by using a render prop. I did this because with "enhanced input components" (like autocomplete), the part we're trying to abstract away is the way it works, and the part we want to grant the most flexibility is the way it looks. In addition, with a render prop, it's trivial for other people to build another component on top of downshift to provide a good default for the way it looks and publish that (I'm still sorta surprised nobody's done that yet). 🤨

Imperfect assumptions

That said, sometimes, the decisions I made about the way downshift works don't quite satisfy all the use cases people are looking to use downshift for. For example, downshift will set the isOpen state of the menu to false when the user selects an item and in the issue @notruth posted, they are saying that decision doesn't fit their use case. 🤷‍♂️

This is one reason why downshift supports control props. It allows you to have complete control over the internal state of downshift. In this case, @notruth could have controlled the isOpen state and use the onStateChange to know when to update their version of that state. However, that's a fair amount of work, so it's understandable why @notruth would prefer an easier method. But the suggestion of adding a new prop for that didn't seem to provide the benefit to offset the cost of increasing the API surface area of downshift. So giving it a little more thought gave me an idea of how we could simplify this and reduce boilerplate further. 😈

A simpler API

That's when I came up with a new prop I initially called modifyStateChange. Because downshift already supports control props, it isolates state changes to an internal method called internalSetState. It's a surprisingly long method (mostly because it's highly commented). This isolation made the implementation of this new feature trivial. Any time we make state changes, we first call a method to see if the user of downshift is interested in making any changes to the state change that's about to take place. 🤓

An important element to this as well is the ability for the user to determine what kind of state change is taking place. In the case of @notruth, they only want to prevent isOpen from changing to false if the user selects (keydown/click) on an item. So they need to know what type of change is about to happen. Luckily, we needed this distinction for onStateChange as well and already had this mechanism in place! It's called stateChangeTypes (here's the current list). 🤖

So, @notruth opened the pull request to add the modifyStateChange. After considering it a little further, I decided that this could be generalized into a pattern that could be really useful for other libraries. Patterns are much easier to evangelize when they have a name, so I looked for one. 🕵️

Introducing the state reducer pattern

I eventually settled on the name "state reducer" and changed the API slightly to resemble a reducer function. Your function gets two arguments: 1) the current state of downshift, 2) the upcoming changes. Your job is to "reduce" that to the changes you want to take place. Also, the upcoming changes have a type that correspond to the stateChangeTypesso you know whether you want your logic to apply. You might think of the changes as an "action" in redux (it has a type), but what you return isn't the whole state (like you would in redux), just the changes you want made to the state. 🔁

A few people have since let me know that reason-react has something similar to this called simply "reducer" which is validating because I think Reason is pretty neat. 💡

So, without further ado, here is a very simple "state reducer" implementation with downshift that prevents the menu from closing after the user selects an item. Here's the stateReducer prop:

import Downshift from 'downshift'

function stateReducer(state, changes) {
	switch (changes.type) {
		case Downshift.stateChangeTypes.keyDownEnter:
		case Downshift.stateChangeTypes.clickItem:
			return {
				...changes,
				isOpen: state.isOpen,
				highlightedIndex: state.highlightedIndex,
			}
		default:
			return changes
	}
}

This is a fairly loose API, but because all the state in downshift is controllable anyway (via control props) this doesn't actually allow you to do anything you weren't already able to accomplish yourself, it just reduces (no pun intended 😆) the boilerplate and wiring that are necessary to tweak "the way it works" with regard to downshift and its state. 👌

The implementation in downshift is probably not altogether straightforward I'm afraid (downshift is not a simple component). Which is why I've created this simplified example implementation for a toggle component: https://codesandbox.io/s/4qo58nvl3x. Note that it's a little bit overkill for a toggle component, but hopefully it gets the point across of one way you could implement this pattern. 🤝

Conclusion

I'm really excited by this new pattern that I see sits in the sweet spot between an uncontrolled and an controlled component. I think it'll do a better job allowing our libraries to satisfy more use cases for "the way it works" without all the boilerplate and wiring up required by users of the Control Props pattern. (And yes, I'll eventually be updating my egghead.io course to include a lesson on the reducer pattern). Good luck! 👍