JotaiJotai

Jotai
React 原始而灵活的状态管理

useReducerAtom

useReducerAtom 是一个自定义钩子,用于将 reducer 应用于原始 atom。

它在临时改变更新行为时非常有用。 另外,对于 atom 级别的解决方案,可以考虑使用 atomWithReducer

import { useCallback } from 'react'
import { useAtom } from 'jotai'
import type { PrimitiveAtom } from 'jotai'
export function useReducerAtom<Value, Action>(
anAtom: PrimitiveAtom<Value>,
reducer: (v: Value, a: Action) => Value,
) {
const [state, setState] = useAtom(anAtom)
const dispatch = useCallback(
(action: Action) => setState((prev) => reducer(prev, action)),
[setState, reducer],
)
return [state, dispatch] as const
}

示例使用

import { atom } from 'jotai'
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 countAtom = atom(0)
const Counter = () => {
const [count, dispatch] = useReducerAtom(countAtom, countReducer)
return (
<div>
{count}
<button onClick={() => dispatch({ type: 'inc' })}>+1</button>
<button onClick={() => dispatch({ type: 'dec' })}>-1</button>
</div>
)
}