Selectors & Subscriptions β
Atomix encourages precise and efficient reactivity through selectors β functions that extract a specific slice of your atom's state. This allows you to subscribe only to the data you care about.
π― What is a Selector? β
A selector is simply a function:
(state) => state.count;
It receives the full state and returns the part you're interested in. Atomix uses this to determine when to trigger listeners.
π‘ Subscribing with a Selector β
const unsubscribe = counterAtom.subscribe(
(state) => state.count,
(count) => {
console.log("Count changed:", count);
}
);
β This only triggers when count changes β not when unrelated parts of the atom state do.
π§ Behind the Scenes β
Under the hood, Atomix shallow-compares the previous and next result of the selector. If theyβre different, the listener runs.
This minimizes unnecessary re-renders or computations.
π React + Selector β
In React, you can use selectors directly with useAtom:
const count = useAtom((state) => state.count)``;
The component will only re-render when state.count changes β not for other keys like state.loading or state.user.
π§Ή Unsubscribing β
If you're using plain JavaScript (outside React), always call unsubscribe() when done:
const stop = atom.subscribe(sel, fn);
// ...
stop();