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

推荐订阅源

L
Lohrmann on Cybersecurity
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
TaoSecurity Blog
TaoSecurity Blog
博客园_首页
Vercel News
Vercel News
Hugging Face - Blog
Hugging Face - Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Last Week in AI
Last Week in AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
The Exploit Database - CXSecurity.com
量子位
Project Zero
Project Zero
A
Arctic Wolf
小众软件
小众软件
NISL@THU
NISL@THU
C
CERT Recently Published Vulnerability Notes
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
P
Privacy & Cybersecurity Law Blog
Security Latest
Security Latest
B
Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
Schneier on Security
Schneier on Security
The Hacker News
The Hacker News
K
Kaspersky official blog
C
Check Point Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Webroot Blog
Webroot Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
人人都是产品经理
人人都是产品经理
AI
AI
Cisco Talos Blog
Cisco Talos Blog
MyScale Blog
MyScale Blog
Cloudbric
Cloudbric
B
Blog RSS Feed
S
Schneier on Security
P
Palo Alto Networks 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 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 How to add testing to an existing project Profile a React App for Performance
The State Initializer Pattern
2021-11-05 · via Kent C. Dodds Blog

When I was working on downshift, I came across a situation where my users (myself included) needed the ability to at any time reset the dropdown we were building to its initial state: no input value, nothing highlighted, nothing selected, closed. But I also had users who wanted the "initial state" to have some default input, default selection, or remain open. So I came up with the state initializers pattern to support all these use cases.

The state initializer pattern allows you to expose an API to users to be able to reset your component to its original state without having to completely unmount and remount the component.

Actually, this pattern is similar in some ways to defaultValue in HTML. Sometimes the consumer of your hook or component wants to initialize the value of your state. The state initializer pattern allows you to do that.

Take this for example:

function Counter() {
	const [count, setCount] = React.useState(0)
	const increment = () => setCount((c) => c + 1)
	const reset = () => setCount(0)
	return (
		<div>
			<button onClick={increment}>{count}</button>
			<button onClick={reset}>Reset</button>
		</div>
	)
}

So our component has a way to initialize its state (to 0) and it also supports a way to reset the state to that initial value.

So what this pattern is for is to allow outside users of your component to control that initial state value. For example. If someone wanted to start the count off as 1 they might want to do this:

<Counter initialCount={1} />

Some libraries that implement this pattern use the prefix default instead of initial to match the defaultValue from the input element. While this makes sense, I still prefer the prefix initial since I feel like it communicates the purpose and use case more clearly.

To support the initialCount prop, here's all we need to do:

function Counter({ initialCount = 0 }: { initialCount?: number }) {
	//              ^^^ accept the prop with a default value so it's optional
	const [count, setCount] = React.useState(initialCount) // <-- pass it to your state
	const increment = () => setCount((c) => c + 1)
	const reset = () => setCount(initialCount) // <-- pass that initialCount value to the reset function
	return (
		<div>
			<button onClick={increment}>{count}</button>
			<button onClick={reset}>Reset</button>
		</div>
	)
}

And here's that with an initial count of 8:

That's the core bit for the pattern. But it is missing one important edge case.

What happens if the user of your component changes the value of initialCount after your component is mounted? Wouldn't that defeat the purpose of the whole "initial" part of our prop name? Here's an example of that where the consumer of our count is changing the initialCount after the initial mount every 500ms:

Clicking "reset" above will reset our component to a different state from its initial state which is probably a mistake, so we want that to not be possible. Click it multiple times and it's getting reset to something completely different every time. Now, I definitely agree with you. This is an example of someone using the API wrong. But if it's not a lot of work we may as well make this impossible right?

So, how can we grab hold of the actual initial value and ignore any changes to that prop? I've got a hint for you. It's not so complicated as useEffect with an isMounted boolean or whatever. It's actually pretty simple. And there are a few ways we could do it:

const { current: initialState } = React.useRef({ count: initialCount })
const [initialState] = React.useState({ count: initialCount })
const [initialState] = React.useReducer((s) => s, { count: initialCount })

// actual initial count is: initialState.count

Between those options, I prefer the useRef, but you do you my friend. Let's do it! Here's that with the initialCount set to 2:

And even if someone were to randomly change the initialCount value, our component wouldn't care.

Resetting state via key

If you've not already read Understanding React's key prop, I recommend you give that a quick read right now. You done? Great, let's continue

One other thing I want to call out is you can actually reset a component pretty easily without any API at all. It's a built-in React API for all components: the key prop. Simply provide a key and set that key prop to a new value any time you want to re-initialize the component. This will unmount and remount the component brand new. Here's the code for that:

function KeyPropReset() {
	const [key, setKey] = React.useState(0)
	const resetCounter = () => setKey((k) => k + 1)
	return <KeyPropResetCounter key={key} reset={resetCounter} />
}

function KeyPropResetCounter({ reset }) {
	const [count, setCount] = React.useState(0)
	const increment = () => setCount((c) => c + 1)
	return <CountUI count={count} increment={increment} reset={reset} />
}

And here's that rendered:

You'll notice that we had to restructure the code a bit to support this. In some situations that may not be possible/desireable.

Additionally, there are more implications to unmounting and remounting a component (which is what changes to the key prop will do). For example, in my Advanced React Patterns workshop, we've got an animation when state changes. Check out the impact of the key approach on that:

With the key reset approach (notice there's no animation):

Clicking a toggle component, then a reset button which shows no animation on reset

With the state initializer pattern (notice there is an animation):

Clicking a toggle component, then a reset button which shows no animation on reset

Also unmounting and remounting components will call useEffect cleanups and callbacks as well. That might be what you want, but it might not be.

Conclusion

The state initializer pattern is pretty simple. In fact, for a long time I removed it from my Advanced React Patterns workshop because I didn't think it was worth the time. But after a few times delivering that workshop without it, people started asking me about the problems it solves so I've added it back. Hope this post helps you in your work. Good luck!