Skip to main content

ion

import { ion } from '@zedux/react'

A factory for creating ion templates. Ions are a type of atom that specialize in selection and derivation operations.

Ions are loosely based off of Recoil's selectors.

Example

Unlike Recoil selectors, ions don't implicitly hijack setState calls. Use exports to explicitly set state where needed.

Live Sandbox
12345678910111213141516171819202122232425262728
const tempFahrenheit = atom('tempFahrenheit', 32)

const tempCelsius = ion('tempCelsius', ({ get, getInstance }) =>
api(((get(tempFahrenheit) - 32) * 5) / 9).setExports({
setTempC: newValue =>
getInstance(tempFahrenheit).setState((newValue * 9) / 5 + 32),
})
)

function TempCelsius() {
const [tempF, setTempF] = useAtomState(tempFahrenheit)
const [tempC, { setTempC }] = useAtomState(tempCelsius)

const addTenCelsius = () => setTempC(tempC + 10)
const addTenFahrenheit = () => setTempF(tempF + 10)

return (
<div>
Temp (Celsius): {Math.round(tempC)}
<br />
Temp (Fahrenheit): {Math.round(tempF)}
<br />
<button onClick={addTenCelsius}>Add 10 Celsius</button>
<br />
<button onClick={addTenFahrenheit}>Add 10 Fahrenheit</button>
</div>
)
}

This is better in pretty much every way imaginable. Exports "just work" with editor go-to definition. They give you more control and they're beautifully explicit which reduces cognitive load, bugs, surprises, all that stuff.

Zedux history

Ions used to have 4 parameters. Back then, the 4th param was the optional config object, and the 3rd was a Recoil-esque setter interceptor. We removed it because exports already handle this, and much more elegantly.

Signature

ion = (key, stateFactory, config?) => newIon
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.
stateFactory

Required. A function that receives an AtomGetters object as its first param and any params of the ion as its rest params. Can return any of the following:

  • A raw value. When the ion template is instantiated, Zedux will create a new store with this value as its initial state.
  • A Zedux store. This will become the atom instance's .store.
  • 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

See Also