selector
Signature
selector<T>(getter: (get: GetFn) => T): Selector<T>valdres Derive computed state that updates automatically
Creates derived state that automatically recomputes when its dependencies change. Selectors are read-only — they compute their value from atoms and other selectors.
Usage
import { atom, selector } from "valdres"
const firstNameAtom = atom("John")
const lastNameAtom = atom("Doe")
const fullNameSelector = selector(get => {
const first = get(firstNameAtom)
const last = get(lastNameAtom)
return `${first} ${last}`
})
Parameters
| Parameter | Type | Description |
|---|---|---|
getter | (get: GetFn) => T | A function that computes the derived value. Use get() to read atoms or other selectors. |
Async selectors
Selectors can also be async. They work with Suspense in React.
const userDataSelector = selector(async get => {
const userId = get(userIdAtom)
const res = await fetch(`/api/users/${userId}`)
return res.json()
})
See also
- selectorFamily — create a collection of selectors keyed by a parameter
- readable — read a selector value in your components