subscribe()
β
The subscribe
method lets you listen to specific parts of an atomβs state. Itβs a powerful way to react to changes without triggering unnecessary work.
π¦ Signature β
ts
subscribe<U>(
selector: (state: T) => U,
listener: (selectedValue: U) => void
): () => void
π§© Parameters β
Name | Type | Description |
---|---|---|
selector | (state: T) => U | Extracts the piece of state to observe |
listener | (selected: U) => void | Runs when selected value changes |
π Return β
Returns a cleanup function:
ts
const unsubscribe = atom.subscribe(selector, listener);
unsubscribe(); // stops listening
β Example β
ts
const counter = createAtom({ count: 0 });
const unsubscribe = counter.subscribe(
(s) => s.count,
(val) => console.log("New count:", val)
);
counter.setState((s) => ({ count: s.count + 1 }));
// β New count: 1
unsubscribe();
β οΈ Selector Comparison β
The selector result is shallow-compared (===). If the value hasnβt changed, the listener will not be called.
Avoid this pattern:
ts
(s) => ({ ...s }); // β always returns a new object
Instead, select primitives or memoized values:
ts
(s) => s.user.id; // β
π§Ό Cleanup β
Always call the unsubscribe function when done (unless using useAtom in React, which handles it automatically).