Skip to main content

injectRef

import { injectRef } from '@zedux/react'

An injector that returns a stable, mutable Ref object. The injector equivalent of React's useRef hook.

The returned Ref object has a .current property that is set initially to the passed value.

Examples

Live Sandbox
1234567891011121314151617181920212223242526
const secondsAtom = atom('seconds', () => {
const ref = injectRef(0)

injectEffect(() => {
const intervalId = setInterval(
() => ref.current++, // doesn't trigger an update
1000
)

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

return ref.current
})

function Seconds() {
const seconds = useAtomValue(secondsAtom)
const instance = useAtomInstance(secondsAtom)

return (
<>
<div>Unchanging Seconds: {seconds}</div>
<button onClick={() => instance.invalidate()}>Force Update</button>
</>
)
}

Miscellaneous:

const ref = injectRef('initial value')
ref.current // 'initial value'
ref.current = { something: 'else' }

const noValRef = injectRef()
noValRef.current // undefined

Exporting a Ref:

import { api, atom, injectRef } from '@zedux/react'

const tableAtom = atom('table', () => {
const tableRef = injectRef(null)

return api().setExports({ tableRef })
})

function Table() {
const { tableRef } = useAtomInstance(tableAtom).exports

return <BigExternalTableComponent ref={tableRef} />
}

Signature

injectRef = (initialValue?) => ref
initialValue

Optional. Can be absolutely anything.

If passed, this will be set as the initial value of the ref's .current property.

This value is discarded on all evaluations but the first.

Returns

A mutable "ref" object with a .current property containing the ref's value.

This object is a stable reference - it will be the same exact object reference every time the current atom instance evaluates.

See Also