Derived state
Computing values from signals — plain closures, memos, Signal<T> props, and slices.
Most values in an interface are computed from other state: the number of unfinished items, whether Save is enabled, a formatted label. Start with a plain closure, and use the other tools on this page when you need caching or a flexible prop type.
Derive a value with a closure
The simplest derived value is a closure. There is nothing to construct.
use zgui::prelude::*;
let items = RwSignal::new(Vec::<Todo>::new());
let remaining = move || items.get().iter().filter(|item| !item.done.get()).count();When remaining() is called inside a tracking context, the signals it reads are subscribed by that
context:
view! {
label {{move || format!("{} left", remaining())}}
}Nothing is cached. If two holes call remaining(), the work runs twice. That is usually fine: a
closure is the cheapest option, has no lifetime to manage, and composes like any Rust function.
Cache a value with Memo
A memo runs its computation once per change and caches the result. It also compares the new result with the old one, and only notifies its readers when the result actually changed.
let over_limit = Memo::new(move |_| count.get() > 10);Memo::new takes impl Fn(Option<&T>) -> T; the argument is the previous value. T must be
PartialEq.
The comparison is the main reason to use a memo. over_limit re-runs on every write to count,
but while the result stays false, nothing downstream runs:
count.set(3); // memo runs, result still false, nothing else runs
count.set(11); // memo runs, result flips, readers runUse a memo when:
- the computation is expensive and read in several places, or
- it reads values that change often but produces a result that changes rarely.
Don't use one for something like a.get() + b.get(); the memo's bookkeeping costs more than the
addition.
Memo<T> requires T: PartialEq + Send + Sync, and there is no local form. For a derived value that
is not Send, use Signal::derive_local.
Two more constructors cover unusual cases:
| Constructor | For |
|---|---|
Memo::new_with_compare(f, changed) | a T without PartialEq, or a custom comparison |
Memo::new_owning(f) | a computation that takes the old value by value and reports whether it changed |
Accept any readable value with Signal<T>
A component shouldn't care whether its caller passes a constant, a signal, a memo or a closure.
A prop of type Signal<T> accepts all of them:
#[component]
fn Badge(
/// The number shown.
count: Signal<i32>,
) -> impl IntoView {
view! {
box(class = "badge") {{move || count.get().to_string()}}
}
}view! {
Badge(count = Signal::stored(5)) // a constant
Badge(count = total.into()) // an RwSignal
Badge(count = doubled.into()) // a Memo
Badge(count = Signal::derive(move || a.get() + 1)) // a closure
}| Constructor | Takes |
|---|---|
Signal::derive(f) | impl Fn() -> T + Send + Sync + 'static |
Signal::derive_local(f) | impl Fn() -> T + 'static, for a T that is not Send |
Signal::stored(v) | a constant T |
Signal::stored_local(v) | a constant T that is not Send |
Read it like any signal: count.get(), count.with(...).
Optional props: MaybeProp<T>
MaybeProp<T> is the same idea for a prop that may be absent, a constant, or a signal.
use zgui::reactive::MaybeProp;
#[component]
fn Field(
/// Shown under the input when present.
#[prop(optional)]
error: MaybeProp<String>,
) -> impl IntoView {
view! {
box {
{move || error.get().map(|message| view! { label(class = "error") {{message}} })}
}
}
}It converts from T, from Option<T>, and, for MaybeProp<String>, from &str.
Props that write: SignalSetter<T>
The write-side counterpart: a prop that accepts a write signal or a closure.
use zgui::reactive::SignalSetter;
#[component]
fn Slider(
/// Called with the new value whenever the handle moves.
on_change: SignalSetter<f32>,
) -> impl IntoView { /* … */ }Create one from a closure with SignalSetter::map(|v| ...).
Callback props are written with an underscore, on_change = …, because they are ordinary props.
Only real event listeners use on:. See Events.
Derive one field of a struct
When state is one struct in one signal but readers care about single fields, create_slice gives a
reader and writer for one field:
use zgui::reactive::create_slice;
let settings = RwSignal::new(Settings::default());
let (theme, set_theme) = create_slice(
settings,
|s| s.theme.clone(),
|s, value| s.theme = value,
);theme is a Signal<Theme> that only notifies when the theme field changes. set_theme is a
SignalSetter<Theme> that writes back into the struct.
For state with many fields and many readers, a store tracks each field without writing slices by hand.
Which to use
| Situation | Use |
|---|---|
| Cheap, read in one or two places | a plain closure |
| Expensive, or read in many places | Memo |
| Recomputed often, but the result rarely changes | Memo |
| A prop that should accept anything readable | Signal<T> |
| The same, but optional | MaybeProp<T> |
| A prop the component writes to | SignalSetter<T> |
| One field of a struct in a signal | create_slice, or a store |