Skip to main content

injectInvalidate

warning

This injector is deprecated and will be removed in the next major release. Use the following pattern instead:

const self = injectSelf()
// then in a callback or effect:
self.invalidate()

See injectSelf()

import { injectInvalidate } from '@zedux/react'

An unrestricted injector that returns an invalidate() function. This invalidate() function can be used to force a reevaluation of the current atom instance.

In general, try to avoid impure, mutation-oriented, or generally non-reactive patterns that might require manual invalidation. However, there are some use cases for it. Specifically when using Query Atoms, this injector may be a key piece of your state flow.

Examples

Live Sandbox
123456789101112131415
const coinTossAtom = atom('coinToss', () => {
const isHeads = Math.random() < 0.5
const invalidate = injectInvalidate()

return api(isHeads).setExports({
flip: invalidate,
})
})

function Coin() {
const isHeads = useAtomValue(coinTossAtom)
const { flip } = useAtomInstance(coinTossAtom).exports

return <button onClick={flip}>{isHeads ? 'Heads' : 'Tails'}</button>
}

injectInvalidate is the equivalent of the following pattern in React:

const [, forceRender] = useState()
...
forceRender({})

(Here's the above example in atom form):

const invalidate = injectInvalidate()
...
invalidate()

Signature

injectInvalidate = () => invalidate
Returns

A function that can be called to force a reevaluation of the current atom instance. Signature:

invalidate = () => void

Only use in callbacks or certain conditions of an effect.

// Don't do this! (would trigger an infinite evaluation loop):
const invalidate = injectInvalidate()
invalidate()

See Also