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

推荐订阅源

cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
雷峰网
雷峰网
Recent Announcements
Recent Announcements
月光博客
月光博客
G
Google Developers Blog
腾讯CDC
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
云风的 BLOG
云风的 BLOG
W
WeLiveSecurity
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - 聂微东
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
P
Privacy International News Feed
MyScale Blog
MyScale Blog
K
Kaspersky official blog
T
The Blog of Author Tim Ferriss
Attack and Defense Labs
Attack and Defense Labs
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
aimingoo的专栏
aimingoo的专栏
I
Intezer
Vercel News
Vercel News
小众软件
小众软件
Simon Willison's Weblog
Simon Willison's Weblog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
Netflix TechBlog - Medium
P
Proofpoint News Feed
Latest news
Latest news
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tor Project blog
S
Security Affairs
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
美团技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Security @ Cisco Blogs
L
LINUX DO - 热门话题
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
D
Docker
L
Lohrmann on Cybersecurity
F
Full Disclosure

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
How to implement useState with useReducer
2019-08-30 · via Kent C. Dodds Blog

Watch "Implement useState with useReducer" on egghead.io

Here's the TL;DR:

const useStateReducer = (prevState, newState) =>
	typeof newState === 'function' ? newState(prevState) : newState

const useStateInitializer = (initialValue) =>
	typeof initialValue === 'function' ? initialValue() : initialValue

function useState(initialValue) {
	return React.useReducer(useStateReducer, initialValue, useStateInitializer)
}

Wanna dive in? Let's go.

But Kent... Why?

For fun 🤓 Also I think that re-implementing things is a great way to learn how they work.

State management in React

React hooks expose two mechanisms for state management: useState and useReducer. Interestingly enough, React actually builds useState out of the same code that's used to build useReducer. They do this because managing a single value of state in a component is very common, but doing that with useReducer would require a bit of boilerplate. So they reduce the boilerplate by exposing a simpler state management API through useState.

They have the benefit of having all their internal code to do this, but we can do this ourselves as well 😄

The useState API

Let's start off by looking at the API that useState exposes to us:

useState function arguments:

You can call useState three different ways:

useState() // no initial value
useState(initialValue) // a literal initial value
useState(() => initialValue) // a lazy initial value

Read more about lazy initial state

So our new useReducer-based useState will need to support all of these argument variations.

useState return value

When you call useState it returns the state and a mechanism for updating that state (commonly called a "state updater function"). That function can be called with the new state or a function which accepts the previous state and returns the new state. So our new useReducer-based useState will need to support both of these variations.

const [state, setState] = useState()
setState(newState)
setState((previousState) => newState)

This is similar to what useReducer does as well, except the mechanism for updating the state is called a "dispatch" function and instead of being used to set the state directly, it delegates the actual state update logic to the reducer.

The useReducer API

So here's the useReducer API:

const [state, dispatch] = React.useReducer(reducerFn, initialValue)

And with useReducer, if you want to have lazy initialization, then you provide a third argument which is your initialization function and the second argument serves as an argument to that initialization function, so you can rename that to something like initialArg.

const initializationFn = (initialArg) => initialArg

const [state, dispatch] = useReducer(reducerFn, initialArg, initializationFn)

And remember, the reducerFn is responsible for what the dispatch function does. So if you want to control how the state is updated by the dispatch function, you can do that via the reducerFn which is called with whatever dispatch is called with.

const reducerFn = (prevState, dispatchArg) => newState

With that, we can implement all the features of useState.

The useReducer-based useState implementation

Here's our starting point:

const useStateReducer = () => {}

function useState() {
	return React.useReducer(useStateReducer)
}

Let's start by trying to implement this use case for the state update function:

const [count, setCount] = useState(0)
setCount(count + 1)

So we need to make the dispatch function actually update the state value. To do that, we make our reducer take the dispatchArg and return that.

const useStateReducer = (prevState, dispatchArg) => dispatchArg

function useState() {
	return React.useReducer(useStateReducer)
}

With that it actually makes more sense to call dispatchArg newState instead:

const useStateReducer = (prevState, newState) => newState

function useState() {
	return React.useReducer(useStateReducer)
}

Great! Next, let's support the function update version of the useState API:

const [count, setCount] = useState(0)
setCount((previousCount) => previousCount + 1)

If we want to continue to support the previous API, we'll need to do some typeof checking to determine whether it's a function and if it is we'll call it with the previous state. Otherwise we'll just return it. Ternaries to the rescue!

const useStateReducer = (prevState, newState) =>
	typeof newState === 'function' ? newState(prevState) : newState

function useState() {
	return React.useReducer(useStateReducer)
}

Nice! Now let's move on to that initial value! For the simple useState(0) case, it's actually really straightforward:

const useStateReducer = (prevState, newState) =>
	typeof newState === 'function' ? newState(prevState) : newState

function useState(initialValue) {
	return React.useReducer(useStateReducer, initialValue)
}

That's it. But what about the lazy version? useState(() => 0) That one's a little more tricky because the useReducer API is slightly different here. Let's iterate to that first. Here's another way we could implement the non-lazy useState(0) use case:

const useStateReducer = (prevState, newState) =>
	typeof newState === 'function' ? newState(prevState) : newState

const useStateInitializer = (initialArg) => initialArg

function useState(initialValue) {
	return React.useReducer(useStateReducer, initialValue, useStateInitializer)
}

In this case we're passing the initialValue as the initialArg and our useStateInitializer function is simply returning that value. This makes it easier to support the lazy initializer version of the API. We simply need to determine whether the initialArg is a function and if it is, we'll call it, otherwise we'll return it.

const useStateReducer = (prevState, newState) =>
	typeof newState === 'function' ? newState(prevState) : newState

const useStateInitializer = (initialValue) =>
	typeof initialValue === 'function' ? initialValue() : initialValue

function useState(initialValue) {
	return React.useReducer(useStateReducer, initialValue, useStateInitializer)
}

And that's it!

Conclusion

I hope you enjoyed digging around these APIs a little bit more with me. I definitely recommend you just continue using the built-in useState hook, but I thought you'd find it interesting to see how flexible useReducer is. You don't have to use it the same way you used redux (in fact, you don't have to use redux in the conventional way either... or at all).

And just for fun, you can play around with this on CodeSandbox if you wanna:

Edit useState implemented by useReducer

Good luck!