zgui

Reactivity in views

Which parts of a view update when state changes — reactive holes, reactive attributes, and what stays fixed.

A view is built once. After that, only the parts you give as a closure or a signal update when state changes; everything else stays as it was built.

What updates

The type of a value decides whether it updates. There is no keyword or annotation.

text {{count.get().to_string()}}          // a String: written once
text {{move || count.get().to_string()}}  // a closure: rewritten when `count` changes

Both compile. The first reads the signal while the view is built and writes the resulting string once. Nothing subscribes, so it never updates.

The second passes a closure. zgui runs it in a tracking context, so the signals it reads are subscribed, and runs it again when they change.

If part of the interface renders correctly once and then never changes, look for a missing move ||.

Reactive holes

A closure child is called a reactive hole: a place in the document that zgui fills with the closure's result and refills when a signal it read changes.

use zgui::prelude::*;

#[component]
fn Status() -> impl IntoView {
    let count = RwSignal::new(0);

    view! {
        column {
            text {{move || count.get().to_string()}}
            text {{move || if count.get() % 2 == 0 { "even" } else { "odd" }}}
            control(on:click = move |_| count.update(|n| *n += 1)) {"+"}
        }
    }
}

Both holes read count. Writing count re-runs those two closures and nothing else in the window.

A hole runs as follows:

  • The first run is synchronous, while the view is built, so there is no empty first frame.
  • Later runs happen at the flush. Several writes before the flush cause one run.
  • An unchanged result writes nothing. If the closure returns the same string as last time, the text node is not touched.
  • Output is updated in place. When the closure returns the same kind of view as last time, the existing nodes are updated rather than replaced. Attributes the new description does not mention keep their old values. Listeners are replaced rather than added, so a handler is never attached twice.

Holes that return elements

A hole can return any view, not only text:

text {{move || format!("{} of {}", done.get(), total.get())}}

box {{move || {
    if let Some(user) = user.get() {
        view! { label {{user.name.clone()}} }
    } else {
        view! { label {"Signed out"} }
    }
}}}

For a two-way choice, prefer if. It only rebuilds when the boolean answer flips. A closure hole re-runs whenever any signal it read changes, and rebuilds what it returns each time, including any components inside it.

Reactive attributes

The same rule applies to attributes. A constant is written once with no effect behind it. A signal or closure gets one effect that keeps the value up to date.

// Constant: written at build time.
box(class = "panel")
box(style:width = "200px")

// Reactive: one effect each.
box(class:open = move || open.get())
box(style:width = move || Some(format!("{}px", width.get())))
box(state:disabled = move || busy.get())

You can pass a signal directly when its value type already matches:

let open: Signal<bool> = /* … */;

box(class:open = open)       // same as `move || open.get()`

Use a closure when there is a computation between the signal and the value.

style:, var: and attr: take an Option<String>, where None removes the value. A literal is wrapped for you, but a closure must return the Option itself: move || Some(format!("{}px", width.get())).

Which values are reactive

You passResult
a literal, or anything Into<T>constant
a closure Fn() -> Treactive
a signal, memo, or other readable Copy handle of Treactive

A component prop can accept all three in the same way. See Derived state.

Common patterns

Toggle a class on a condition

row(
    class = "todo",
    class:done = move || item.done.get()
)

class sets the fixed classes. class:done adds and removes one class as the closure's result changes. The fixed classes are never rewritten.

Combine several signals in one text

label {{move || format!("{} of {} done", done.get(), total.get())}}

One hole with two subscriptions. A write to either re-runs it once.

Share an expensive value

let summary = Memo::new(move |_| expensive(rows.get()));

view! {
    text {{move || summary.get()}}
}

A memo computes once per change and caches the result, so several holes can share it. See Derived state.

What does not update

// An element name. To switch elements, use `if` or `Dynamic`.
column { … }

// A value read outside a closure, even if it came from a signal.
let label = count.get().to_string();
view! { text {{label}} }

// A listener. It is attached once.
control(on:click = handler)

// An untracked read. This hole runs once and subscribes to nothing.
text {{move || count.get_untracked().to_string()}}

When a hole is removed

A reactive hole belongs to the scope it was built in. When its component or branch is removed, the hole's effect is disposed of in the same frame, along with anything created under it, such as timers. You do not need to keep a handle to it. Effects you create by hand work differently; see Effects and lifecycle.

Next

On this page