An atom is the smallest unit of state: a token you create once and read or write through a store, while derived atoms compute their value from other atoms and stay in sync automatically. This is the model behind Jotai — atoms are stateless tokens, and a store holds every atom's actual value so the same atom can be shared across independent stores. You build a tiny version of it: atom to declare state, and createStore to read, write, and subscribe.
type Atom = object; // an opaque, stateless token — holds no value of its own
const miniJotaiAtoms: {
// atom(initialValue) → primitive atom
// atom(read) → derived atom, read = (get) => computedValue
// atom(read, write) → writable derived atom (optional)
atom(readOrInitial: unknown, write?: Function): Atom;
createStore(): {
get(atom: Atom): unknown; // current value (init on first read)
set(atom: Atom, value: unknown): void; // update a primitive / run a write fn
sub(atom: Atom, cb: () => void): () => void; // subscribe; returns unsubscribe
};
};
const { atom, createStore } = miniJotaiAtoms;
const count = atom(0); // primitive atom
const doubled = atom((get) => get(count) * 2); // derived atom
const store = createStore();
store.get(count); // 0
store.get(doubled); // 0
store.set(count, 5);
store.get(doubled); // 10 — recomputed from count
const count = atom(0);
const store = createStore();
const unsub = store.sub(count, () => console.log('changed'));
store.set(count, 1); // logs "changed"
store.set(count, 1); // same value — logs nothing
unsub();
store.set(count, 2); // logs nothing — unsubscribed
atom() returns an opaque token; every value lives in the store, so one atom used in two stores holds two independent values.get(otherAtom); the store records those reads and recomputes only when one of them changes, returning a cached value otherwise.Object.is, notifies nobody.