injectCallback
import { injectCallback } from '@zedux/react'
An injector that memoizes a function and wraps it in an ecosystem.batch()
call. This is essentially a shorthand for the following:
const { ecosystem } = injectAtomGetters()
const setTwoStores = injectMemo(
() => (stateA, stateB) => {
ecosystem.batch(() => {
storeA.setState(stateA)
storeB.setState(stateB)
})
},
[]
)
// equivalent using injectCallback:
const setTwoStores = injectCallback((stateA, stateB) => {
storeA.setState(stateA)
storeB.setState(stateB)
}, [])
The returned function reference will only change when the passed dependencies change on subsequent evaluations.
Can be useful when exporting functions from an atom to ensure that you're only exporting stable references.
Miscellaneous:
import { injectCallback, injectMemo } from '@zedux/react'
const add = injectCallback((a: number, b: number) => a + b, [])
const withDeps = injectCallback(myFn, [depA, depB])
// to prevent automatic batching, use `injectMemo` instead ...
const withoutBatching = injectMemo(() => myFn, [depA, depB])
// ... or use an inline function if memoization isn't needed:
const inlineCallback = myFn
Signature
- Simplified
- TypeScript
injectCallback = (callback, deps?) => callback
declare const injectCallback: <Args extends any[] = [], Ret = any>(
callback: (...args: Args) => Ret,
deps?: InjectorDeps
) => (...args: Args) => Ret
Optional (though you'll always want to pass it). An array containing absolutely anything.
If any items in this array change on a subsequent evaluation, the previously memoized callback will be discarded, replaced with the newly-passed function.
Pass an empty array to prevent the returned callback reference from ever changing, as long as this atom instance is alive.
The memoized callback function. The returned reference will only change if any deps change.