🎣 useReducer

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

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