Skip to main content

atom

import { atom } from '@zedux/react'

Where it all starts. atom() is a factory for creating atom templates. These templates are actually instances of the AtomTemplate class. Atom templates are passed to many of Zedux's hooks and injectors. They tell Zedux how to create their atoms.

Example

Live Sandbox
12345678910111213141516171819202122232425262728293031323334
const simpleAtom = atom('simple', 'Hello, world!')

const complexAtom = atom(
'complex',
() => {
const store = injectStore({ date: new Date() })

injectEffect(() => {
const intervalId = setInterval(
() => store.setState({ date: new Date() }),
1000
)

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

return store
},
{
flags: ['side-effect'],
}
)

function App() {
const simple = useAtomValue(simpleAtom)
const { date } = useAtomValue(complexAtom)

return (
<>
<div>simple state: {simple}</div>
<div>complex state: {date.toLocaleTimeString()}</div>
</>
)
}
atom = (key, valueOrFactory, config?) => newAtom
key

Required. A string.

This key must be unique except when creating atom overrides.

The key is the key to Dependency Injection - it's how ecosystems know which atom templates to override. It also aids development - many errors will log the key of the atom they originated in. Keys also help with a codebase's grepability.

It is possible for plugins to hook into the instanceReused mod and check for potentially problematic duplicate keys. Though HMR makes that difficult.

valueOrFactory

Required. Can be any of the following:

  • A raw value. When the atom is instantiated, Zedux will create a new store with this value as its initial state.
  • A Zedux store. This will be the store of this atom's instance - "instance" singular because such an atom will naturally be a singleton (meaning it doesn't take params, since a state factory function wasn't passed).
  • A state factory function that returns a raw value. Zedux will create a new store with the returned value as its initial state.
  • A state factory function that returns a Zedux store. The returned store will be the instance's .store.
  • A state factory function that returns an AtomApi instance.

    The Atom API's value can be any of the following:

    • A raw value. Zedux will create a new store with this value as its initial state.
    • A Zedux store. This will be the instance's .store.
    • A promise. This will turn the atom into a query atom.

    The Atom API's exports will be set as the atom instance's .exports.

    The Atom API's promise will be set as the atom instance's .promise.

config

Optional. An AtomConfig object.

Returns

An atom template. This template is actually an instance of the AtomTemplate class.

Zedux will manage creating and maintaining instances of the atom template as you use it.

See Also