The atom() function is the core primitive for storing and updating mutable state in Reatom. Atoms can be called as functions to read their current value or updated using the .set() method.
Subscribe to state changes. The callback is called immediately with the current state, then whenever the state changes. Returns an unsubscribe function.
import { atom } from '@reatom/core'// Create an atom with an initial valueconst counter = atom(0, 'counter')// Read the current valueconst value = counter() // -> 0// Update with a new valuecounter.set(5) // Sets value to 5// Update with a functioncounter.set((prev) => prev + 1) // Sets value to 6
// Lazily compute the initial stateconst timestamp = atom(() => Date.now(), 'timestamp')// The function is only called once during initializationconst value = timestamp() // -> 1234567890
// Create an atom that starts as undefinedconst maybeValue = atom<string>()maybeValue() // -> undefinedmaybeValue.set('hello')maybeValue() // -> 'hello'
interface Atom<State = any, Params extends any[] = [newState: State]> extends AtomLike<State, []> { // Update with a new value set(...params: Params): State // Update with a function set(update: (state: State) => State): State}