useValdresCallback

Signature
useValdresCallback(callback: (set, get, reset) => Fn, deps): Fn

valdres-react Recoil-style callback hook

useCallback with store access: the outer function receives set, get, and reset and returns your event handler. The handler runs inside a transaction, so multiple updates commit atomically. Equivalent to Recoil's useRecoilCallback.

Usage

import { atom } from "valdres"
import { useValdresCallback } from "valdres-react"

const cartAtom = atom<string[]>([])
const totalAtom = atom(0)

function AddButton({ id, price }: { id: string; price: number }) {
    const add = useValdresCallback(
        (set, get) => () => {
            set(cartAtom, [...get(cartAtom), id])
            set(totalAtom, get(totalAtom) + price)
        },
        [id, price],
    )
    return <button onClick={add}>Add</button>
}

The component doesn't subscribe to cartAtom or totalAtomget reads the current value at call time without causing re-renders.

See also