Selector<T, U>
β
A Selector in Atomix is a function that extracts a specific part of the atomβs state.
It allows you to:
- Subscribe only to what you care about
- Reduce unnecessary re-renders or listener calls
- Improve performance in both React and vanilla JS
π§± Type Definition β
ts
type Selector<T, U> = (state: T) => U;
β Example β
ts
const counterAtom = createAtom({ count: 0, name: "Naol" });
const countSelector = (state: { count: number }) => state.count;
const unsubscribe = counterAtom.subscribe(countSelector, (val) => {
console.log("Count:", val);
});
βοΈ With React β
Selectors work the same way inside useAtom:
ts
const count = useAtom(counterAtom, (state) => state.count);
β React component only re-renders when count changes.
π« Anti-Patterns β
Avoid selectors that return new objects or functions every time:
ts
(s) => ({ ...s }); // β always creates a new object
(s) => new Date(); // β always new value
π‘ Tip β
Selectors should return stable values (e.g., strings, numbers, booleans, object references) to ensure === comparison is meaningful.