Skip to main content

injectMemo

import { injectMemo } from '@zedux/react'

An injector that memoizes a value. This is the injector equivalent of React's useMemo() hook. Like useMemo(), injectMemo() will return the same value on subsequent evaluations unless any items in the dependency array change.

Example

Live Sandbox
1234567891011121314151617181920212223242526272829
const secondsAtom = atom('seconds', () => {
const store = injectStore(0)

injectEffect(() => {
const intervalId = setInterval(() => store.setState(val => val + 1), 1000)

return () => clearInterval(intervalId)
}, [])

return store
})

const everyFifthAtom = atom('everyFifth', () => {
const seconds = injectAtomValue(secondsAtom)

return injectMemo(() => seconds, [Math.floor(seconds / 5)])
})

function Seconds() {
const seconds = useAtomValue(secondsAtom)
const everyFifth = useAtomValue(everyFifthAtom)

return (
<>
<div>Seconds: {seconds}</div>
<div>Every Fifth Second: {everyFifth}</div>
</>
)
}

Miscellaneous:

const constantVal = injectMemo(() => getExpensiveVal(), [])

const changesWhenDepsChange = injectMemo(getExpensiveVal, [depA, depB])

const changesEveryTimeButJustWhy = injectMemo(getExpensiveVal)

Signature

injectMemo = (valueFactory, deps?)
valueFactory

Required. A function that returns the value to memoize.

This function is called on initial evaluation and again every time any dependencies change on subsequent evaluations.

deps

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 value will be discarded and the valueFactory will be called again to produce a new value.

Pass an empty array to prevent the value from ever changing, as long as this atom instance is alive.

Returns

The memoized value returned from the valueFactory.

See Also