zgui

Effects and lifecycle

Run your own code when state changes with RenderEffect, clean up with on_cleanup_local, keep untracked state in StoredValue, know when components mount, rebuild and unmount, and reach elements through NodeRef.

Most reactive work in zgui happens in holes and attributes that the view creates and owns. When you need to run your own code in response to state, such as focusing a field, measuring an element or syncing an outside resource, you write an effect. This page covers effects, cleanup, untracked state, the component lifecycle, and NodeRef for working with elements directly.

When to write an effect

A reactive hole such as text {{move || count.get().to_string()}} is already an effect: it reads signals, writes a text node, and re-runs when they change. The view owns it, so you never create or cancel it.

Write an effect yourself only when the work is something a view cannot describe:

The workWhere it belongs
a value in the documenta reactive hole
a class, style or attribute that follows statea reactive attribute
a subtree that appears or disappearsif or for
focusing, scrolling, measuring or selecting in a nodean effect over a NodeRef
a listener on a node this view did not createan effect over a NodeRef
a file, socket, device or other outside resourcean effect
a non-reactive object kept in sync with a signalan effect

Do not use an effect only to write a signal that the view reads. That adds an extra effect run on every change. Compute the value in a closure or a Memo instead.

Run code when state changes

RenderEffect is zgui's effect type. The view layer is built on it.

use zgui::prelude::*;
use zgui::reactive::{RenderEffect, flush};

let count = RwSignal::new(1);
let doubled = RwSignal::new(0);

let effect = RenderEffect::new(move |_| doubled.set(count.get() * 2));

assert_eq!(doubled.get(), 2);   // the first run happened inside the constructor
count.set(21);
assert_eq!(doubled.get(), 2);   // the write only marked the effect
flush();
assert_eq!(doubled.get(), 42);  // the flush ran it

flush() stands in for the frame loop here. Applications never call it.

  • The first run happens immediately, inside RenderEffect::new.
  • Later runs happen at the next flush. Five writes between two frames cause one run. Effects woken by other effects in the same flush also run in that flush.
  • The effect lives as long as its handle. Dropping the handle stops it. It is not tied to the current owner.

The closure does not need to be Send. Effects run on the UI thread and may capture node handles, listener guards and other local values.

Keep the effect alive

An effect whose handle is dropped runs once and never again:

// Dropped at the end of the statement.
RenderEffect::new(move |_| println!("{}", count.get()));

RenderEffect is #[must_use], so this warns. let _ = RenderEffect::new(…) drops it just the same, without a warning.

A let in a component body is not enough either: the binding goes out of scope when the body returns. Move the handle into a cleanup, which lives exactly as long as the component:

use zgui::reactive::RenderEffect;

#[component]
fn ThemeToggle(dark: RwSignal<bool>) -> impl IntoView {
    // Save the choice to disk whenever it changes.
    let saving = RenderEffect::new(move |_| save_preference("dark", dark.get()));
    on_cleanup_local(move || drop(saving));

    view! {
        control(
            class = "theme",
            on:click = move |_| dark.update(|dark| *dark = !*dark)
        ) {"Toggle theme"}
    }
}

React to a change instead of a value

The closure receives what its previous run returned (None on the first run) and returns the value for the next run. Use it to act only when a value changes:

let watching = RenderEffect::new(move |was: Option<bool>| {
    let closing = closing.get();
    if closing && was != Some(true) {
        start_exit();   // only on the run where `closing` became true
    }
    closing
});

Each run disposes of the previous run's scope first, so signals and cleanups created inside the closure belong to that run only.

ItemWhat it does
RenderEffect::new(fun)fun: impl FnMut(Option<T>) -> T + 'static. Runs fun immediately.
RenderEffect::new_with_value(fun, initial)The same, with the value the first run receives.
effect.with_value_mut(|v| …)Borrows the value the last run returned. Returns Option<U>.
effect.take_value()Takes that value, leaving None.

Effect, untrack and batch are not available

zgui does not export the reactive engine's plain Effect. Its thread-safe constructors can run the closure off the UI thread, where touching the document is a data race. Using it fails to compile:

error[E0433]: cannot find `Effect` in `zgui_reactive`

The engine's on_cleanup (which requires Send + Sync) and unkeyed store indexing are also left out. Use RenderEffect and on_cleanup_local.

There is no untrack: use the _untracked read methods. There is no batch: writes never run anything synchronously, so all writes between two flushes already coalesce.

Clean up when a scope ends

pub fn on_cleanup_local(cleanup: impl FnOnce() + 'static);

on_cleanup_local registers a closure that runs once, when the current owner is disposed of. The owner is the component's scope, an if branch's, a for row's, or an effect run's.

use std::cell::Cell;
use std::rc::Rc;
use zgui::reactive::{Mounted, on_cleanup_local};

let cancelled = Rc::new(Cell::new(false));

let node = Mounted::new();
node.with({
    let cancelled = Rc::clone(&cancelled);
    move || on_cleanup_local(move || cancelled.set(true))
});

assert!(!cancelled.get());
node.unmount();
assert!(cancelled.get());   // before `unmount` returned

A cleanup runs when:

  • the component, branch or row it was registered in unmounts,
  • the component it was registered in rebuilds (see Rebuild),
  • the window closes, or the application ends,
  • the effect it was registered in runs again.

Cleanups run in registration order, with no current owner. Capture what the cleanup needs when you register it.

The closure does not need to be Send, so it can capture node handles, guards and effects. It runs on the thread that registered it. In debug builds, on_cleanup_local panics if there is no current owner or if it is called off the UI thread. In release builds with no owner, the closure is dropped and never runs.

The other APIs for values that are not Send follow the same pattern: RwSignal::new_local(v) for a signal's value and provide_local_context(v) for a context value.

The component lifecycle

A component mounts once, may rebuild any number of times, and unmounts once.

Mount

  1. The body runs in a new scope. #[component] creates the scope, so every signal, context, stored value, task and cleanup created in the body belongs to it. A NodeRef created here is still unbound.
  2. The view is built. Elements are created, attributes applied, reactive holes run for the first time, and children built. node_ref attributes bind here.
  3. The subtree is inserted into the document. Style, layout and paint follow in the same frame. Geometry is available once that frame completes.

Rebuild

A component inside a reactive hole is rebuilt when the hole runs again and produces the same component. zgui keeps the existing nodes, cleans the component's scope (running its cleanups, cancelling its tasks and freeing its signals), runs the body again in the same scope, and updates the nodes in place.

An if branch keeps its own scope while the condition's answer stays the same. Writes that leave the answer unchanged do not dispose of anything the branch created. When the component around the if rebuilds, the shown branch is rebuilt too.

Unmount

  1. Nodes are removed, innermost first: children unmount, then each element's bindings are dropped, then the element is detached.
  2. The scope is disposed of: child scopes first, then cleanups in registration order, then everything the scope allocated.

Unmounting is synchronous. When it returns, timers are cancelled, observers removed, effects stopped, tasks cancelled and signals freed.

Closing a window unmounts its view the same way, in tree order, while application-wide context is still available. When the application ends, every window's view is unmounted before run returns.

Reading a signal after its owner was disposed of panics. Use try_get or try_with where the value may be gone. A NodeRef never panics: a handle whose element is gone answers None.

Keep state that does not trigger updates

A StoredValue<T> holds a value in the reactive arena without tracking. Reading it subscribes to nothing and writing it notifies nothing. Use it for cached handles, generation counters, guards that must stay alive, and scratch state shared between listeners.

use zgui::prelude::*;

#[component]
fn Slider(offset: RwSignal<f32>) -> impl IntoView {
    // Where the press started. Two listeners share it; nothing displays it.
    let origin: StoredValue<Option<f32>> = StoredValue::new(None);

    view! {
        box(
            class = "slider",
            on:pointer_down = move |ev| origin.set_value(Some(ev.position.x.0)),
            on:pointer_move = move |ev| {
                if let Some(start) = origin.get_value() {
                    offset.set(ev.position.x.0 - start);
                }
            },
            on:pointer_up = move |_| origin.set_value(None)
        )
    }
}
SignalStoredValue
Reading subscribesyesno
Writing notifiesyesno
Copyyesyes
Freed whenits owner is disposed ofits owner is disposed of
Read withget, with, readget_value, with_value, read_value
Write withset, update, writeset_value, update_value, write_value

The method names differ so that a stored value read in a reactive hole, which would never update, stands out.

StoredValue::new(v) requires T: Send + Sync. StoredValue::new_local(v) accepts any T and keeps it on the creating thread; use it for listener guards, closures and other local values.

Work with elements through NodeRef

A NodeRef is a handle to one element in the document. Use it for the imperative things a view cannot describe: focusing, scrolling, measuring, selecting, and attaching listeners to nodes you did not create.

use zgui::prelude::*;
use zgui::reactive::RenderEffect;

/// A search box that takes focus when it appears.
#[component]
fn Search(open: Signal<bool>) -> impl IntoView {
    let input = NodeRef::new();

    // Re-runs when the panel opens and again when the field is bound.
    let focusing = RenderEffect::new(move |_| {
        if open.get() && input.get().is_some() {
            input.focus();
        }
    });
    on_cleanup_local(move || drop(focusing));

    view! {
        if move || open.get() {
            row(class = "search") {
                field(class = "search__input", node_ref = input)
            }
        }
    }
}

NodeRef is Copy and belongs to the scope that created it. The node_ref attribute binds it when the element is built. To run code once an element exists, read get() in an effect and act when it is Some.

When the element that bound the handle goes away, the handle becomes unbound. If a newer element bound the same handle first (for example, the other branch of an if), the handle keeps the newer element.

An unbound handle never fails. Its methods return None, "", 1.0, false or a default, and a handle whose node no longer exists behaves the same way.

Only get() tracks. is_bound(), bounds() and the other getters read without subscribing. An effect waiting for the element must read get(), or it runs once with an empty handle and never again.

Act on an element

MethodWhat it does
focus()moves focus to this node
scroll_to(target, behavior)requests a scroll
set_value(&str)sets the text of an editable node; no-op if unchanged
selection(), set_selection(range), select_all()the selection in an editable node
focusables() -> Vec<NodeId>focusable descendants, in traversal order
focus_move(direction) -> Option<NodeId>moves focus within this subtree
trap_focus(options) -> Option<FocusTrap>confines Tab traversal to this subtree until the guard drops
window_shortcut() -> Option<WindowShortcut>lets this node hear keys while something else has focus, until the guard drops
listen(event, options, handler) -> Option<ListenerGuard>attaches a listener until the guard drops

Use listen for nodes you did not create, such as the window root from window_root(). Dropping the guard removes the listener, so keep it in a StoredValue::new_local or in the effect's returned value.

Read geometry

These methods read the last completed frame. Layout is never run on demand.

MethodReturns
bounds() -> Option<Rect<DevicePx, Device>>the box, with its origin relative to the parent's border box
window_bounds() -> Option<Rect<DevicePx, Device>>the box in window coordinates
scale() -> f32device pixels per CSS pixel; 1.0 when unbound
text_content() -> Stringall text in the subtree, in order
scroll_position() -> ScrollPositionoffset, content extent and visible extent
scroll_offset() -> Point<DevicePx, Device>the offset alone
running_animations() -> usizeanimations and transitions running on the node

Pointer positions are in CSS pixels in window space. bounds() is in device pixels relative to the parent. Compare a pointer with window_bounds() instead, after multiplying by scale():

let track_box = track.window_bounds()?;
let x = ev.position.x.0 * track.scale();
let fraction = (x - track_box.origin.x.0) / track_box.size.width.0;

Track size and scroll as signals

The observe_* methods turn geometry into signals, so a view can follow an element's size or scroll position. A signal is written during the frame that changed the value, before paint, so a view that positions itself from a measurement is painted correctly in that same frame.

#[component]
fn Ruler() -> impl IntoView {
    let track = NodeRef::new();
    let size = track.observe_content_size();

    view! {
        column {
            box(class = "ruler__track", node_ref = track)
            text {{move || format!("{:.0} px", size.get().width.0)}}
        }
    }
}
MethodSignalReports
observe_border_box()Signal<Option<Rect<DevicePx, Device>>, LocalStorage>where the border box is drawn in the window, with every transform applied; a transformed box is reported as its upright bounding rectangle
observe_border_size()Signal<Option<Size<DevicePx, Device>>, LocalStorage>the size from observe_border_box, without the position
observe_content_size()Signal<Size<DevicePx, Device>, LocalStorage>the content area's size, before transforms
observe_scroll()Signal<ScrollPosition, LocalStorage>offset, content extent and visible extent
observe_*_while(active)the samewatched only while active returns true
  • A signal is written only when the quantity it watches changes. Prefer observe_border_size() when you do not need the position: moving one edge of a panel moves everything inside it, and a size-only observation ignores those moves.
  • Observations are shared per node and per quantity, so many observers cost the same as one.
  • You can observe in the component body, before the element is built. Observation starts when the handle binds, and the Option signals read None until the first value arrives.
  • active is reactive. A view that is only sometimes visible costs nothing while hidden.

Identity and position in the tree

MethodReturns
NodeRef::new()an unbound handle owned by the current scope
get() -> Option<NodeId>the node. Tracks. None before binding and after the element is gone
get_untracked() -> Option<NodeId>the same, without subscribing
is_bound() -> boolwhether it currently names a node
contains(other: NodeId) -> boolwhether other is this node or inside it
is_within(ancestor: NodeId) -> boolwhether this node is ancestor or inside it
precedes(other: NodeId) -> boolwhether this node comes first in document order
window_root() -> Option<NodeRef>a handle to the root element of this node's window

Check that effects are enabled

The reactive engine compiles effects behind a Cargo feature, and another crate in the dependency graph can resolve that feature away. Everything still builds and the first frame renders, but no view ever updates again. Guard against this at startup:

fn main() -> Result<(), zgui::Error> {
    assert!(zgui::reactive::effects_are_enabled());

    app().with_title("Editor").run(|| view! { Editor() })
}

effects_are_enabled() builds an effect, writes a signal it reads, flushes, and reports whether it re-ran. It takes microseconds.

Troubleshooting

SymptomCauseFix
The effect runs once and never again.The handle was dropped: a bare statement, let _ = …, or a let in a component body.Move it into on_cleanup_local(move || drop(effect)).
Nothing reactive updates, with no warning.Effects were compiled out by another crate in the graph.assert!(effects_are_enabled()) at startup, then fix the manifest.
The effect keeps running after its component is gone.Something longer-lived holds the handle: a context, a global, a parent's StoredValue.Keep the handle in the scope whose lifetime it should have.
Memory grows by one entry per mount.Each mount adds a handle to a collection that is never emptied.Same fix. Assert the collection's length in a test.
Panic: Dereferenced SendWrapper<T> variable from a thread different to the one it has been created with.A local value was touched off the UI thread.Keep reactive work on the UI thread; use RenderEffect.
A cleanup never runs, in release builds only.It was registered with no current owner.Register it in a component body or effect.
The log reports a task that exceeded its budget.Two effects write each other's sources. One task is polled at most 8 times per flush in release builds and 32 in debug builds, then deferred.Break the cycle by deriving one value instead of writing it.
State created in a component resets unexpectedly.The component was rebuilt by a hole around it, which cleans its scope.Move the state to the parent, or use if/Show so unrelated writes do not rebuild it.

Next

On this page