useTransaction
Signature
useTransaction(store?: Store): (callback: (txn: Transaction) => any) => anyvaldres-react Batch updates — subscribers fire once
Returns a function that runs a callback as a transaction on the current store: all updates apply atomically and subscribers fire once at the end. The callback receives { set, get, reset, del, unset }.
Usage
import { atom } from "valdres"
import { useTransaction } from "valdres-react"
const firstNameAtom = atom("")
const lastNameAtom = atom("")
function ResetForm() {
const txn = useTransaction()
const clear = () =>
txn(({ reset }) => {
reset(firstNameAtom)
reset(lastNameAtom)
})
return <button onClick={clear}>Clear</button>
}
Pass a store to target one explicitly: useTransaction(myStore).
See also
- Transactions guide — semantics, nesting, and performance
- useValdresCallback — memoized callback with transactional set/get
- useStore — access the current store