Back to Jotai

Callback

docs/utilities/callback.mdx

2.20.01.4 KB
Original Source

useAtomCallback

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

Usage

ts
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

jsx
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>
}

Stackblitz

<Stackblitz id="vitejs-vite-ekxjhs" file="src%2FApp.tsx" />