Skip to main content

useAtomContext

import { useAtomContext } from '@zedux/react'

A React hook that accepts an atom template and returns an instance of that atom template that has been provided over React context via <AtomProvider>.

If no instance has been provided, this hook will return undefined. Pass default params as the second argument to tell Zedux to create an atom instance if one wasn't provided. Pass true as the second argument to tell Zedux to throw an error if you forgot to provide an instance.

This hook will not register a graph dependency of any kind on the provided instance. You can create a graph dependency by passing the consumed atom instance to various hooks:

note

This is one of the few hooks that does not have an injector equivalent (there is no such thing as injectAtomConsumer()). This is because this hook's functionality is very specific to React. There is no equivalent in the atoms universe.

Example

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

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

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

return store
})

function Child() {
const instance = useAtomContext(secondsAtom)
const state = useAtomValue(instance)

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

function Parent() {
const instance = useAtomInstance(secondsAtom)

return (
<AtomProvider instance={instance}>
<Child />
</AtomProvider>
)
}

Miscellaneous:

const instance = useAtomContext(myAtom)

const defaulted = useAtomContext(myAtom, ['param 1', 'param 2'])

// if the atom doesn't take params, pass an empty array for the default params:
const defaultedNoParams = useAtomContext(myAtom, [])

// passing `true` makes Zedux throw an error if no instance was provided:
const guaranteed = useAtomContext(myAtom, true)

Signature

useAtomContext = (template, defaultParamsOrThrow?) => atomInstance
template

Required. An atom template.

defaultParamsOrThrow

Optional. Can be either:

  • An array containing valid params of the passed atom.
  • A boolean.

If an array (defaultParams) is passed, useAtomContext() will use it to find or create an atom instance if none was provided above the current component via an <AtomProvider>. If the atom doesn't take params, pass an empty array.

If true is passed, useAtomContext() will throw an error if the current component is rendered outside a matching <AtomProvider>. This is the recommended overload. Example:

const instance = useAtomContext(myAtom, true)
Returns

An atom instance of the passed atom template.

If no instance was provided and default params were passed, returns the instance matching the given params. If the instance doesn't exist yet, useAtomContext() uses the passed template and default params to create it.

If no instance was provided and true is passed as the 2nd parameter, this hook throws an error.

See Also