🎣 useReducer
20 Jan, 2023
👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page
- Docs: http://reactjs.org/docs/hooks-reference.html#usereducer
- TS/React docs: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/blob/master/README.md#hooks
Example Jump to heading
import React, { useReducer } from 'react'
const initialState = { count: 0 }
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }
case 'decrement':
return { count: state.count - 1 }
default:
throw new Error()
}
}
export const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
)
}
useImmer Jump to heading
For complex stuff, useImmer is a great option
← Back home