Skip to main content

AtomProvider

import { AtomProvider } from '@zedux/react'

A component that provides one or more atom instances over React context.

To consume the provided instances, use useAtomContext().

Example

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

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

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

return store
})

function Child() {
const instance = useAtomContext(secondsAtom) // no need to pass params
const state = useAtomValue(instance) // subscribe

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

function Parent() {
const instance = useAtomInstance(secondsAtom, [100])

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

Providing multiple instances:

<AtomProvider instances={[instanceA, instanceB]}>{children}</AtomProvider>

Props

AtomProvider accepts either an instance prop with a single atom instance OR an instances prop with an array of instances. You must pass one or the other but not both.

instance

A single atom instance. This instance will be provided over React context.

instances

An array of atom instances. Each instance will be provided with a separate React context provider.

Be careful reordering this list and adding/removing items since this will make React destroy/recreate the entire component subtree inside <AtomProvider>.

See Also