Skip to main content

Crate rok_ui_hooks

Crate rok_ui_hooks 

Source
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

ReactThis crate
useState(v)use_state → (ReadSignal, WriteSignal)
useEffect(fn, deps)use_effect / use_effect_with
useMemo(fn, deps)use_memo → Memo
useReduceruse_reducer
useRef(v)use_ref → Rc<RefCell<T>>
useContext(ctx)use_context
createContext / <Provider>create_context / with_provider
Solid createRootcreate_root, Root
Solid createEffectcreate_effect
Solid createRenderEffectcreate_render_effect
create() + useStore(s, sel)create_store + use_store
createSelectorStore::select
createResourceuse_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:

depsmeaning
()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.

featurebringslives in
storecreate_store, Store, use_storestore.rs
contextcreate_context, use_context, with_providercontext.rs
keyedcreate_keyed_list, KeyedListkeyed.rs
asyncspawn, Task, use_resourceexecutor.rs, resource.rs
timersuse_debounced, use_throttledtimer.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:

  • tick compiles down to flush when timers and async are 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.rs stays compiled even with context off. runtime.rs re-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/*.md files, the README and every example assume the default features, because between them they cover the whole surface. Targets in Cargo.toml declare required-features, so cargo test --no-default-features skips them instead of failing.

§Where to look next

  • README.md and docs/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.md for the model, docs/api-reference.md for every item, docs/async-and-time.md for the tick loop, docs/patterns.md for idioms and pitfalls, docs/architecture.md for the internals, and docs/porting.md for 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.
KeyedList
A live list of keyed rows, each with its own owned scope.
Memo
A cached derived value.
OwnedRoot
A scope that outlives the call that created it. Dropping it disposes everything created inside.
ReadSignal
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.
WriteSignal
The write half of a signal — you cannot read a tracked value through it.

Enums§

ResourceState
What a Resource knows right now.

Traits§

DepItem
One element of a deps tuple.
Deps
A whole deps tuple, evaluated and compared as a unit.

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 explicit crate::flush.
create_effect
createEffect(fn, deps) — the Solid-flavoured name of use_effect.
create_keyed_list
Build a keyed list. Rows render once; use KeyedList::reconcile to diff.
create_memo
createMemo(fn, deps) — the Solid-flavoured name of use_memo.
create_owned_root
Create a long-lived owned scope. See OwnedRoot.
create_render_effect
useEffect(fn, deps) where fn returns a cleanup callback, deferred to the next frame. The create_render_effect counterpart of use_effect_with.
create_root
Run f in a fresh root and dispose it before returning — the scoped form of Root.
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 f without 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) — run f now, and again when a dependency changes.
use_effect_with
useEffect(fn, deps) where fn returns a cleanup callback.
use_memo
useMemo(fn, deps) — recompute f when 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 value source had 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) → a Resource that starts fetching immediately.
use_resource_with
createResource that maps a future’s output through select, 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 of f.