Skip to main content

useAtomValue

import { useAtomValue } from '@zedux/react'

A React hook that accepts an atom template and its params and registers a dynamic graph dependency on the resolved atom instance, returning the value.

The component that uses this hook will rerender whenever the resolved atom instance's state changes.

If the resolved atom instance doesn't exist yet, useAtomValue() creates it.

Example

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

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

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

return store
})

function Seconds() {
const state = useAtomValue(secondsAtom)

return <div>Seconds: {state}</div>
}

Miscellaneous:

const val = useAtomValue(myAtom)
const withParams = useAtomValue(myAtom, ['param 1', 'param 2'])
const fromInstance = useAtomValue(instance)

Signature

useAtomValue = (atomOrInstance, params?) => state
atom

Required. An atom template or atom instance.

If an atom template is passed, you must also pass any required params of the atom.

If an atom instance is passed, the params are ignored. In this case, useAtomValue() returns the current value of the passed instance (essentially instance.getState()).

In all cases, useAtomValue() adds a dynamic dependency on the resolved atom instance.

params

Required if the passed atom template takes required params. Optional if not.

Don't pass this or pass an empty array if the atom does not take params or if passing an atom instance.

Returns

The current value of the resolved atom instance's store.

Uses the passed atom template + params combo to find an existing atom instance. If no instance is found, useAtomValue() creates one using the template and params and returns its initial value.