Back to Jotai

Reducer

docs/utilities/reducer.mdx

2.19.1516 B
Original Source

atomWithReducer

Ref: https://github.com/pmndrs/jotai/issues/38

js
import { atomWithReducer } from 'jotai/utils'

const countReducer = (prev, action) => {
  if (action.type === 'inc') return prev + 1
  if (action.type === 'dec') return prev - 1
  throw new Error('unknown action type')
}

const countReducerAtom = atomWithReducer(0, countReducer)

Stackblitz

<Stackblitz id="vitejs-vite-bbpmjn" file="src%2FApp.tsx" />

useReducerAtom

See useReducerAtom recipe.