Expand description
Fine-grained reactivity with a React-flavoured API.
Components — if you write any — run once. Work is organised into effects, which re-run when the signals they read change, and memos, which recompute lazily when somebody reads them. No component tree is ever re-executed, so adding state never costs a re-render.
use rok_ui_hooks::*;
let (count, set_count) = use_state(0);
let doubled = use_memo(
{ let count = count.clone(); move || count.get() * 2 },
(),
);
let _effect = use_effect(
{
let (count, doubled) = (count.clone(), doubled.clone());
move || println!("count = {}, doubled = {}", count.get(), doubled.get())
},
(doubled,),
);
set_count.set(2); // count = 2, doubled = 4§The mental model
The graph has three kinds of node, and the difference between them is the whole design:
- signals hold a value. They have no dependencies. A write bumps a version and marks what reads them.
- memos are derived values. They are lazy: a marked memo recomputes when somebody reads it, and its readers only wake up if the value really changed.
- effects are side effects. They are eager: a marked effect is queued and runs when the enclosing batch ends.
A write runs nothing synchronously, which is what makes any graph shape
glitch-free — see batch, untrack and flush for the controls, and
Root for scope.
§Mapping to React and Solid
| React | This crate |
|---|---|
useState(v) | use_state → (ReadSignal, WriteSignal) |
useEffect(fn, deps) | use_effect / use_effect_with |
useMemo(fn, deps) | use_memo → Memo |
useReducer | use_reducer |
useRef(v) | use_ref → Rc<RefCell<T>> |
useContext(ctx) | use_context |
createContext / <Provider> | create_context / with_provider |
Solid createRoot | create_root, Root |
Solid createEffect | create_effect |
Solid createRenderEffect | create_render_effect |
create() + useStore(s, sel) | create_store + use_store |
createSelector | Store::select |
createResource | use_resource |
<For each={…}> | create_keyed_list |
onCleanup(fn) | on_cleanup, use_cleanup |
§Dependencies
A deps argument is a tuple of handles and/or plain values; it is
re-evaluated on every notification, so a handle contributes its current
value:
| deps | meaning |
|---|---|
() | no declared deps: re-run when anything the body read changes |
(count,) | re-run only when count has a new value (React [count]) |
(0i32,) | constant: mount only (React []) |
§Features
Everything above is core and always compiled: signals, memos, effects, deps,
ownership, batch, untrack, flush, use_reducer,
use_previous and OwnedRoot. The rest sits behind five features —
all of which are on by default, so a plain dependency gets the whole
surface and nothing changes for an existing user.
| feature | brings | lives in |
|---|---|---|
store | create_store, Store, use_store | store.rs |
context | create_context, use_context, with_provider | context.rs |
keyed | create_keyed_list, KeyedList | keyed.rs |
async | spawn, Task, use_resource | executor.rs, resource.rs |
timers | use_debounced, use_throttled | timer.rs, part of hooks.rs |
Turn the default set off and ask for what you actually use:
[dependencies]
rok-ui-hooks = { version = "0.3", default-features = false, features = ["store", "async"] }full is an alias for all five, so default = ["full"] and
features = ["full"] mean the same thing.
Three consequences worth knowing before you trim:
tickcompiles down toflushwhentimersandasyncare both off, because there is then no deadline and no task to advance. It still exists, so your loop does not need a conditional.- The provider machinery in
context.rsstays compiled even withcontextoff.runtime.rsre-installs a captured provider stack on every run of every node and that is not feature-dependent, so the feature removes the public API, not the plumbing. - The
docs/*.mdfiles, the README and every example assume the default features, because between them they cover the whole surface. Targets inCargo.tomldeclarerequired-features, socargo test --no-default-featuresskips them instead of failing.
§Where to look next
README.mdanddocs/getting-started.md— the guided tour.- The
examples/directory:demo,advanced,todo_app,ownership,keyed_list,async,context_demo,hooks_demo,store_demo. docs/concepts.mdfor the model,docs/api-reference.mdfor every item,docs/async-and-time.mdfor the tick loop,docs/patterns.mdfor idioms and pitfalls,docs/architecture.mdfor the internals, anddocs/porting.mdfor moving from React, Solid, or the 0.1 API.- Every code block in the README and
docs/is compiled as a doctest, so the documentation cannot drift from the code.
Structs§
- Context
- A typed context, comparable to React’s
createContext(defaultValue). - Debounced
- A signal that only reports its source once the source stopped changing for a quiet period.
- Dispatch
useReducer(reducer, initialState)→(state, dispatch).- Effect
- Owning handle to a running effect. Dropping it disposes the effect.
- Keyed
List - A live list of keyed rows, each with its own owned scope.
- Memo
- A cached derived value.
- Owned
Root - A scope that outlives the call that created it. Dropping it disposes everything created inside.
- Read
Signal - The read half of a signal — you cannot write through it.
- Resource
- An asynchronous value with request state, cancellation and latest-wins semantics.
- Root
- A disposable scope. Computations created inside
Root::run— directly or in an effect body — are disposed together when the root goes away. - Store
- A reactive state container: readable and writable like a signal, observable by
plain listeners, and selectable with
Store::select. - Subscription
- Handle returned by
Store::subscribe; dropping it unsubscribes. - Task
- A spawned future.
- Throttled
- A signal that reports at most once per window: the first change goes through immediately, the rest are coalesced into one trailing update.
- Write
Signal - The write half of a signal — you cannot read a tracked value through it.
Enums§
- Resource
State - What a
Resourceknows right now.
Traits§
Functions§
- batch
- Group writes: effects are queued and each one runs at most once per flush.
- create_
context createContext(defaultValue).- create_
deferred_ effect - Like
use_effect, but re-runs wait for an explicitcrate::flush. - create_
effect createEffect(fn, deps)— the Solid-flavoured name ofuse_effect.- create_
keyed_ list - Build a keyed list. Rows render once; use
KeyedList::reconcileto diff. - create_
memo createMemo(fn, deps)— the Solid-flavoured name ofuse_memo.- create_
owned_ root - Create a long-lived owned scope. See
OwnedRoot. - create_
render_ effect useEffect(fn, deps)wherefnreturns a cleanup callback, deferred to the next frame. Thecreate_render_effectcounterpart ofuse_effect_with.- create_
root - Run
fin a fresh root and dispose it before returning — the scoped form ofRoot. - create_
signal createSignal(v)→(read, write).- create_
store create(fn)→ a store holding the initial state.- flush
- Run every queued effect, deferred ones included.
- on_
cleanup onCleanup(fn)— register teardown for whatever is running right now: the computation, else the nearest owner.- pending_
tasks - How many tasks are still alive. Useful in diagnostics and tests.
- shallow_
array_ eq - Element-wise equality for fixed-size arrays.
- shallow_
vec_ eq - Element-wise equality for
Vecs, whatever their capacity and pointer. - spawn
- Spawn a future on the local executor. It is polled at the next
crate::tick, and again each time it wakes itself. - tick
- Advance the world by one frame: fire due timers, poll woken tasks, then run every pending effect.
- untrack
- Run
fwithout subscribing the current observer to anything it reads. - use_
cleanup onCleanup(fn)— register teardown for the effect, memo or owner that is running. It fires before that computation re-runs and when it is disposed.- use_
context useContext(ctx)— tracked read of the nearest provider value.- use_
debounced useDebounced(source, quiet)— the trailing edge of a burst of writes.- use_
effect useEffect(fn, deps)— runfnow, and again when a dependency changes.- use_
effect_ with useEffect(fn, deps)wherefnreturns a cleanup callback.- use_
memo useMemo(fn, deps)— recomputefwhen a dependency changes, and notify readers only when the produced value actually differs.- use_
memo_ eq useMemo(fn, deps)with your own equality test.- use_
previous usePrevious(value)— the valuesourcehad the last time this was read.- use_
reducer useReducer(reducer, initialState).- use_ref
useRef(initial)— a stable mutable box, handy for counting runs or holding something you do not want to be a dependency.- use_
resource createResource(fetcher)→ aResourcethat starts fetching immediately.- use_
resource_ with createResourcethat maps a future’s output throughselect, so only the projected value lands in the resource.- use_
state useState(initial)→(state, set_state).- use_
store useStore(store, selector)— a tracked selector read. Use it inside an effect (or any observer) and the observer re-runs whenever the store changes.- use_
throttled useThrottled(source, window)— leading edge plus one trailing update.- with_
provider <Ctx.Provider value={value}>— push a value for the dynamic extent off.