zgui

Signals

Reactive state — creating signals, reading and writing them, tracking, and when updates run.

A component's body runs once, so anything that changes later has to live in a signal. A signal holds a value. zgui records which code read it, and runs that code again when the value changes.

Why signals

Plain variables do not stay connected:

let mut count = 0;
let label = count.to_string();

count += 1;
// `label` still says "0".

An interface is full of values derived from state: a window title from the document name, a disabled Save button from whether there is anything to save. Each must be recomputed when its inputs change, and only then. Signals make this automatic: because zgui records what read a signal, a write updates exactly that code and nothing else.

Create a signal

use zgui::prelude::*;

let count = RwSignal::new(0);

assert_eq!(count.get(), 0);
count.set(1);
assert_eq!(count.get(), 1);

RwSignal<T> is a handle you can read and write. It is Copy, so you can move it into any number of closures without cloning. The value lives in a reactive arena; the handle is a small index.

ReadSignal and WriteSignal

signal creates the same state but returns a separate reader and writer, as in Your first application:

// One handle that reads and writes.
let count = RwSignal::new(0);
count.update(|n| *n += 1);

// A separate reader and writer.
let (count, set_count) = signal(0);
set_count.update(|n| *n += 1);

signal(0) returns (ReadSignal<T>, WriteSignal<T>). Split them when one part of the code should only read and another should only write, so the types say who may do what. Both are Copy.

Tracking

A tracking context is code that zgui runs and watches: an effect, a memo, or a reactive hole in a view. A read inside one subscribes that context to the signal. A read outside one does not. A write marks every subscriber to run again.

let count = RwSignal::new(0);

// Not tracked: a one-off read.
let snapshot = count.get();

// Tracked: this effect now depends on `count`.
let effect = RenderEffect::new(move |_| {
    println!("count is {}", count.get());
});

Dependencies are found by running the code, not declared. If a closure reads three signals on one run and one signal on the next, its dependencies change to match.

A read outside a tracking context gives the right value once and never updates. Nothing warns you. This is the most common reactive bug: the interface renders once and then stays frozen.

Read and write

Reads and writes are trait methods, so use zgui::prelude::*; must be in scope. Because they are traits, a function can accept anything readable as a T.

MethodWhat it does
get()clones the value out and subscribes
with(|v| ...)borrows the value and subscribes, without cloning
read()returns a guard that derefs to the value, and subscribes
set(v)replaces the value and marks subscribers
update(|v| ...)mutates in place and marks subscribers
write()returns a mutable guard; marks subscribers when dropped

get() needs T: Clone. For large values, use with or read:

let items = RwSignal::new(vec![1, 2, 3]);

let total: i32 = items.with(|items| items.iter().sum());   // no clone
let copy = items.get();                                    // clones the Vec

Read without subscribing

Each read has an _untracked form (get_untracked, with_untracked, read_untracked) that reads without subscribing.

let draft = RwSignal::new(String::new());

// Read the current text once, without subscribing.
let text = draft.get_untracked();

Use it where not subscribing is the point, such as reading a value once during setup. Event listeners are not tracking contexts, so an ordinary get() there is fine too; _untracked just makes the intent explicit.

There is no untrack block as in some other reactive libraries. The _untracked form marks the exact read that should not subscribe.

When updates run

Writing a signal does not run its subscribers. It only marks them. The frame loop then runs a flush, which runs each marked subscriber once.

use zgui::reactive::{RenderEffect, RwSignal, 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);   // a render effect runs once, immediately
count.set(21);
assert_eq!(doubled.get(), 2);   // the write only marked the effect
flush();
assert_eq!(doubled.get(), 42);  // the flush ran it

An application never calls flush() itself; the frame loop does. As a result, many writes in one listener cause one update, not many:

// Five writes, one update pass.
on:click = move |_| {
    first.set(1);
    second.set(2);
    third.set(3);
    fourth.set(4);
    fifth.set(5);
}

This is why zgui has no batch function: all writes between two flushes already cause at most one run per subscriber.

The signal itself is up to date immediately: reading it back in the same listener returns the new value. Only the code that depends on it waits for the flush.

Structs and collections

A signal can hold any type:

#[derive(Clone, Debug, PartialEq)]
struct Filter {
    text: String,
    only_open: bool,
}

let filter = RwSignal::new(Filter { text: String::new(), only_open: false });

filter.update(|f| f.only_open = true);

A write notifies every reader of the signal, whatever part changed. If parts of a struct change independently and have different readers, split it into several signals or use a store, which tracks each field separately.

A signal per item

For a list, a common pattern is a Vec of items where each item holds a signal for the part that changes:

#[derive(Clone, Debug)]
struct Todo {
    id: u64,
    label: String,
    done: RwSignal<bool>,
}

let items = RwSignal::new(Vec::<Todo>::new());

Adding or removing an item writes items. Ticking an item writes only its done, so code that reads the list does not run again.

Where to create signals

A signal belongs to the owner that was current when it was created. Owners are scopes: a component body runs inside one, and when the component is removed, its owner disposes of the signals created there.

#[component]
fn Panel() -> impl IntoView {
    let open = RwSignal::new(false);   // owned by this component, freed with it
    // ...
}

A signal created with no current owner, such as in a static, a lazily initialised global, or a thread you spawned, is never freed. Create signals in component bodies, or in an owner you manage. For application-wide state, create it at the root and share it through context.

Threads

Starting the application makes the calling thread the UI thread. All reactive work, such as effects, memos and view updates, runs there.

Thread-safe signals can be read and written from other threads, and a write from a worker schedules a frame. Still, owners and effects are UI-thread-only, so do not use signals as your main channel between threads. From a worker, send results back with a Ui handle and Ui::post; see Background work.

Values that are not Send

By default a signal's value must be Send + Sync. Values from the view layer, such as node handles and Rc callbacks, are not. Store them in a local signal:

use std::rc::Rc;
use zgui::reactive::{LocalStorage, RwSignal};

let handle: RwSignal<Rc<str>, LocalStorage> = RwSignal::new_local("a".into());
assert_eq!(&*handle.get(), "a");

Reading a local signal from another thread panics. Contexts and cleanup closures have local forms too, covered in Context and Effects and lifecycle. If the compiler complains about a missing Send or Sync near reactive state, a local form is usually the fix.

Common mistakes

SymptomCause
The interface renders once and never changes.A signal was read outside a tracking context.
A dependent value looks stale right after a write.Dependents update at the flush, not at the write.
A whole list re-runs when one row changes.One signal holds both the collection and each row's state. Give rows their own signals.
Memory grows with state that is never freed.Signals were created with no owner.
The build fails on Send/Sync.The value is not thread-safe; use new_local.

Next

On this page