useAtomCallback
引用: https://github.com/pmndrs/jotai/issues/60
使用
useAtomCallback(callback: (get: Getter, set: Setter, arg: Arg) => Result): (arg: Arg) => Promise<Result>
这个 hook 允许与原子进行命令式交互。 它需要一个像原子写函数一样工作的回调函数, 并返回一个返回承诺的函数。
传递给 hook 的回调必须是稳定的(应该用 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(await readCount());}, 1000);return () => {clearInterval(timer);};}, [readCount]);return <div>current count: {count}</div>;};