JotaiJotai

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

Callback

useAtomCallback

参考: https://github.com/pmndrs/jotai/issues/60

使用方法

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

这个钩子用于命令式地与原子进行交互。 它接受一个回调函数,该函数的工作方式类似于原子写入函数, 并返回一个返回原子值的函数。

传递给钩子的回调必须是稳定的(应该用 useCallback 包装)。

示例

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