An atom is the fundamental building block of Reatom’s state management system. It represents a mutable state container that can be read, updated, and subscribed to for changes.Atoms are reactive primitives that:
Store a single value of any type
Can be updated directly with new values
Automatically notify subscribers when their value changes
Track dependencies when read inside computed values
import { atom } from '@reatom/core'// Create with initial valueconst counter = atom(0, 'counter')// Create with a factory functionconst timestamp = atom(() => Date.now(), 'timestamp')// Create without initial value (will be undefined)const optionalValue = atom<string>()
Always provide a name as the second parameter for better debugging and DevTools support.
interface Atom<State = any, Params extends any[] = [newState: State]> { // Read the current state (): State // Update with a function set(update: (state: State) => State): State // Set a new value set(newState: State): State // Subscribe to changes subscribe(cb?: (state: State) => any): Unsubscribe // Extension system extend: Extend<this>}
Use a factory function for expensive initial state computation:
// Computed only once when first accessedconst expensiveData = atom(() => { console.log('Computing initial data...') return processLargeDataset()}, 'expensiveData')// Factory only runs on first read or subscriptionexpensiveData()