State and Derived Values
Use state and derived values with the current published Askr packages.
@askrjs/askr0.0.59
How to use state and derived values
Start with this complete state and derived values shape, then replace the example data and application service with your own.
- Import the published @askrjs/askr entrypoint.
- Keep state and derived values configuration next to the component, route, or server composition root that owns it.
- Handle pending, unavailable, cancellation, and failure states, then verify the production path.
import { derive, state } from '@askrjs/askr';
const quantity = state(2);
const unitPrice = state(12);
const total = derive(() => quantity() * unitPrice());Create state
Call `state(initialValue)` inside a component to allocate a piece of local state; it returns a callable getter combined with a `.set()` method, destructurable as `const [count, setCount] = state(0)`. Under the hood each call records itself against the current component instance, so calling `state()` outside of render — at module scope or inside an event handler — throws instead of silently creating orphaned state.
Read and update state
Read a state cell by calling it, `count()`, and update it by calling `setCount(nextValue)` or `setCount(prev => prev + 1)` when the next value depends on the previous one. Reading state inside a component body is what wires that component up to future updates; reading it outside render (in a plain callback, for instance) just returns a snapshot without subscribing to anything.
Derived values
`derive(fn)` computes a value from other reactive sources and re-evaluates only when one of those sources changes, returning a `Derived<T>` that's callable just like state. It also supports a two-argument form, `derive(source, map)`, for mapping over another readable source such as a resource or query result. Because derived values are read the same way as state, you can swap one for the other without touching the calling code.
Selectors and subscriptions
`selector(source, equals?)` builds a fine-grained subscription: it watches `source()` and returns a predicate you call with a candidate value to check equality, so a component only re-renders when that specific comparison flips rather than whenever the underlying source changes at all. The optional `equals` function lets you customize comparison beyond `===`, which matters for objects or normalized IDs. This is the tool for list items or tabs that need to know "am I the selected one" without subscribing to the whole selection value.