JotaiJotai

状態
Primitive and flexible state management for React

Callback

useAtomCallback

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

Usage

useAtomCallback<Result, Args extends unknown[]>(
callback: (get: Getter, set: Setter, ...arg: Args) => Result,
options?: Options
): (...args: Args) => Result

This hook is for interacting with atoms imperatively. It takes a callback function that works like atom write function, and returns a function that returns an atom value.

The callback to pass in the hook must be stable (should be wrapped with useCallback).

Examples

import { useEffect, useState, useCallback } from 'react'
import { Provider, atom, useAtom } from 'jotai'
import { useAtomCallback } from 'jotai/utils'
const countAtom = atom(0)
const Counter = () => {
const [count, setCount] = useAtom(countAtom)
return (
<>
{count} <button onClick={() => setCount((c) => c + 1)}>+1</button>
</>
)
}
const Monitor = () => {
const [count, setCount] = useState(0)
const readCount = useAtomCallback(
useCallback((get) => {
const currCount = get(countAtom)
setCount(currCount)
return currCount
}, []),
)
useEffect(() => {
const timer = setInterval(async () => {
console.log(readCount())
}, 1000)
return () => {
clearInterval(timer)
}
}, [readCount])
return <div>current count: {count}</div>
}

Codesandbox