useSelector
Creates a selection set over source.
Creates a selection set over source. isSelected(key) answers whether key matches the
current source value. Reading it inside an effect or memo subscribes only to that key's boolean,
so when the source changes from a to b only the readers of a and b re-run, with the
default equality. A custom equals costs one call per registered key per change.
The source is tracked by a render-phase effect in the current owner. Create the selector before
its consumers, so that each consumer runs once per change. Calling isSelected outside a tracked
context reads the source directly and creates no subscription. The default equality is ===,
so NaN never matches.
Import#
ts
import { useSelector } from "@shadow-js/core";
Signature#
ts
function useSelector<T, K = T>(
source: () => T,
equals?: (key: K, value: T) => boolean,
): (key: K) => boolean
Parameters#
| Name | Description |
|---|---|
source |
The value that selects keys. Tracked. |
equals |
Optional (key, value) => boolean. Undefined uses key === value. |
Returns#
isSelected(key).
Throws#
- Nothing itself. When a custom
equalsthrows during a change, the other keys are still updated and the error goes to the owner's error handler. In development, a selector created outside any owner warnsNO_OWNER_EFFECT.
Examples#
ts
import { mapArray, useSelector, useSignal } from "@shadow-js/core";
function Rows(props: { ids: number[] }) {
const [selectedId, setSelectedId] = useSignal(1);
const isSelected = useSelector(selectedId);
return mapArray(() => props.ids, (id) => (
<li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>
));
}