useReducerAtom
useReducerAtom
은 기본 아톰에 리듀서를 적용하기 위한 커스텀 훅입니다.
이 훅은 업데이트 동작을 일시적으로 변경할 때 유용합니다. 또한 아톰 수준의 해결책을 원한다면 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 + 1if (action.type === 'dec') return prev - 1throw new Error('알 수 없는 액션 타입')}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>)}