/
🎣

useReducer

react
Table of contents
  • Example
  • useImmer
  • Docs: reactjs.org/docs/ho...nce.html
  • TS/React docs: github.com/typescri...EADME.md

Example

tsx
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

For complex stuff, useImmer is a great option

Want to make your own site like this? Try gatsby-theme-code-notes by Zander Martineau.
Notes on code. My second brain, by Zander Martineau.