zgui

Context and ownership

Pass a value to a deep child with context, and how owners decide when reactive values are freed.

Context lets a component provide a value once and have any component below it read that value, without passing it through every component in between. Context is built on owners, the tree of scopes that also decides when signals and other reactive values are freed. The first half of this page covers context; the second half covers owners.

Pass a value to a deep child

Without context, a value a deep child needs is passed as a prop through every component in between:

#[component]
fn Page(theme: RwSignal<bool>) -> impl IntoView {
    // `Page` does not use `theme`; it only passes it on.
    view! { Sidebar(theme = theme) }
}

With context, you provide the value once and read it anywhere below. The components in between do not mention it:

#[derive(Clone, Copy)]
struct Theme(RwSignal<bool>);

#[component]
fn App() -> impl IntoView {
    provide_context(Theme(RwSignal::new(false)));
    view! { Page() }
}

#[component]
fn ThemeButton() -> impl IntoView {
    let Theme(dark) = expect_context::<Theme>();
    view! {
        control(on:click = move |_| dark.update(|on| *on = !*on)) { "Toggle theme" }
    }
}

use_context returns Option<T>; expect_context panics when nothing above provides a T, which suits components that cannot work outside their parent.

A context lookup is not a reactive read, and update_context notifies nothing. To make a context drive the interface, put a signal inside it and write the signal, as every example here does.

Look a context up once in the component body and keep the result in a local. A lookup walks up the tree of owners, so a lookup inside a reactive closure repeats that walk on every run.

A listener runs in the scope it was written in, so use_context also works inside a click handler, and a signal created there belongs to the component.

How lookup works

A context is keyed by its type. provide_context stores the value on the current owner. A lookup starts at the current owner and walks towards the root, returning the first value of that type it finds.

  • A nested provider shadows an outer one of the same type, for its subtree only.
  • Providing twice in one scope replaces the first value.
  • Lookups only go up. A sibling's or a child's context is invisible.
  • A miss returns None, never a default.

Use a newtype as the key

The key is the type, shared across the whole process. Wrap anything whose type is not specific to your use:

// Wrong: the second call replaces the first.
provide_context(String::from("en-GB"));   // the locale
provide_context(String::from("dark"));    // the theme

// Right.
#[derive(Clone)] struct Locale(String);
#[derive(Clone)] struct ThemeName(String);

provide_context(Locale("en-GB".into()));
provide_context(ThemeName("dark".into()));

In the wrong version, use_context::<String>() returns "dark" with no error. Avoid bool, u32, String and Rc<str> as context types.

Example: a theme and a selection

A theme and a selection, provided once and read at two different depths:

use zgui::prelude::*;

#[derive(Clone, Copy)]
struct Theme(RwSignal<bool>);

#[derive(Clone, Copy)]
struct Selection(RwSignal<Option<u64>>);

#[component]
fn App() -> impl IntoView {
    provide_context(Theme(RwSignal::new(false)));
    provide_context(Selection(RwSignal::new(None)));

    let Theme(dark) = expect_context::<Theme>();

    view! {
        column(class = "app", class:dark = move || dark.get()) {
            Toolbar()
            List()
        }
    }
}

#[component]
fn Toolbar() -> impl IntoView {
    let Theme(dark) = expect_context::<Theme>();

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

#[component]
fn List() -> impl IntoView {
    let rows = RwSignal::new(vec![1_u64, 2, 3]);

    view! {
        column(class = "list") {
            for id in move || rows.get(), key = |id: &u64| *id {
                Row(id = id)
            }
        }
    }
}

#[component]
fn Row(id: u64) -> impl IntoView {
    // `List` never mentions the selection.
    let Selection(selected) = expect_context::<Selection>();

    view! {
        row(
            class = "row",
            class:selected = move || selected.get() == Some(id),
            on:click = move |_| selected.set(Some(id)),
        ) {
            text {{format!("Row {id}")}}
        }
    }
}
  • App provides in its own body, so its own view can read the context too.
  • The context values are Copy because they hold signal handles, not data. use_context clones, so cheap values are best.

When setup takes more than a line, wrap it in a provider component: a ThemeProvider that takes children: Children, calls provide_context and returns {children.into_view_once()}. Everything inside it sees the context.

Share a context across windows

A context a component provides belongs to that component's window. Other windows do not see it.

Use with_context on the application builder for state every window must see, or that must survive a suspend. It runs in the application owner before the first window opens:

#[derive(Clone, Copy)]
struct Count(RwSignal<i32>);

fn main() -> Result<(), zgui::Error> {
    app()
        .with_context(|| provide_context(Count(RwSignal::new(0))))
        .run(|| view! { Counter() })
}

The runtime provides Fonts, Windows and Clipboards in the application owner, so use_context::<Fonts>(), use_windows() and use_clipboard() work from every window. Fonts is also visible inside with_context.

Provide a value that is not Send

provide_context requires T: Send + Sync. View-layer values such as node handles, Rc callbacks and backend handles are not. Use the local variants:

use std::rc::Rc;

#[derive(Clone)]
struct PanelHandle(Rc<str>);

provide_local_context(PanelHandle("panel".into()));
let handle = use_local_context::<PanelHandle>();
  • A local context may only be touched on the thread that created it. use_local_context panics if the value came from another thread, and in debug builds both functions panic off the UI thread.
  • A local context and a provide_context::<T> of the same type do not collide, because the local value is stored under a wrapper type. For the same reason with_context, update_context and take_context cannot see a local context. Read it only with use_local_context.

The framework uses this itself: each window provides its host with provide_local_context, which is how free functions such as set_timeout and focused_node find the right window.

Owners

A signal handle is Copy and is moved into closures that outlive the function that made it, so Rust's scoping cannot free it. Owners do. An owner is a node in a tree of scopes, and one owner is current at any moment. Reactive values created while it is current attach to it:

Attaches to the current ownerExample
arena-backed handlesRwSignal, ReadSignal, WriteSignal, Memo, Signal, Store
stored valuesStoredValue
contextsvalues passed to provide_context
cleanupsclosures passed to on_cleanup_local
child ownersone per nested component, list row or branch

Two exceptions:

  • The reference-counted forms (ArcRwSignal, ArcMemo, ArcSignal, …) attach to no owner. They are freed when the last handle drops.
  • A RenderEffect lives as long as its handle. Dropping the handle cancels it. The view layer keeps that handle in the node's state, so the effect goes with the node.

Owners the framework creates

You rarely create an owner yourself. The framework creates these:

OwnerCreated byDisposed of when
applicationthe runtime, above every windowthe application ends
windowthe runtime, once per open windowthe window closes, or the platform suspends it
component#[component], around each callthe component is unmounted; it is also cleaned before its body re-runs on a rebuild
list rowfor / Forthat row's key leaves the collection
branchif / Showthe branch is replaced

So a signal created in a component body is freed when the component leaves the interface, and a row's signals are freed when that row is deleted, not when the whole list is.

A branch is replaced only when the condition's answer changes. A write the condition reads but that leaves the answer the same keeps the branch, and everything it created, alive.

When a window closes, its view is unmounted and every scope it made is disposed of, while the application owner is still alive. On resume after a suspend, each window's owner and view are built again under the application owner.

Disposal

Disposing of an owner runs synchronously, before the call returns:

  1. Its child owners are disposed of, depth first.
  2. Its cleanups run, in the order they were registered.
  3. Its arena-backed values are dropped.

Because nothing is deferred, a removed node's timers, observers and table slots are gone in the same frame. Reading a handle after its owner is disposed of panics:

At src/main.rs:41:18, you tried to access a reactive value which was defined at
src/main.rs:12:21, but it has already been disposed.

Use try_get, try_with or try_update when a closure may legitimately outlive the value it reads; they return None instead.

Values created with no owner

Creating a signal with no current owner succeeds. The handle works, but it is never registered, so it is never freed. There is no panic and no log, in any build.

// No owner is current here.
let count = RwSignal::new(41);
count.set(42);
assert_eq!(count.get(), 42);   // works, and leaks for the life of the process

Four operations check for an owner, and panic in debug builds when there is none (the check compiles away in release):

  • provide_context
  • provide_local_context
  • on_cleanup_local
  • Selector::is_selected (see Stores and selectors)

The message names the fix:

provide_context requires a current owner: with none, the value it creates is unreachable and
never freed. Run it inside `Mounted::with`.

Do not put a signal in a static or a lazily initialised global. Its initialiser runs on first read: either with no owner, so it leaks silently, or inside whichever component read it first, so it is disposed of when that component unmounts and every later read panics. Put shared state in a context provided at the root instead.

Debug builds also log two warnings at error level through tracing (they never panic):

LimitLogged when
owner depth 4096one owner chain is deeper than this: owners are nested and never disposed of
1024 childrenone owner has created more children than this without retiring them (see Scope)

Create a scope with Mounted

Mounted is a scope you create and dispose of yourself. The runtime uses it for window roots; tests use it to drive a view outside a window.

impl Mounted {
    pub fn new() -> Self;
    pub fn with<T>(&self, build: impl FnOnce() -> T) -> T;
    pub fn owner(&self) -> &Owner;
    pub fn unmount(self);
}
use zgui::prelude::*;
use zgui::reactive::{Mounted, install};

install().unwrap();          // an application does this for you
let node = Mounted::new();
let count = node.with(|| RwSignal::new(0));

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

node.unmount();              // `count` is gone; reading it now panics
  • Mounted::new() with no current owner creates a root. Inside another scope's with, it creates a child that is disposed of with its parent.
  • It is #[must_use]. Dropping it also disposes of it (including during a panic), but call unmount explicitly.
  • Cleanups run with no owner current. Capture everything a cleanup needs when you register it.
  • In debug builds, creating one off the UI thread panics.

Manage many short-lived scopes with Scope

An owner keeps an entry for every child it has ever created, even after the child is disposed of. A long-lived parent with short-lived children, such as a scrolling list, grows without bound. Scope fixes this by grouping children into generations and dropping a generation once all its members are gone.

Use Scope only when you mount and unmount a changing set of sibling scopes yourself. for lists already do this internally.

use zgui::reactive::Scope;

impl Scope {
    pub fn new() -> Self;
    pub fn mount(&self) -> Mounted;
    pub fn live(&self) -> usize;
    pub fn generation_children(&self) -> usize;
    pub fn generations_created(&self) -> usize;
}
let scope = Scope::new();
let pinned = scope.mount();      // stays mounted the whole time

for _ in 0..10_000 {
    let row = scope.mount();
    // ... build the row ...
    row.unmount();
}

assert_eq!(scope.live(), 1);
assert!(scope.generation_children() < 100);
pinned.unmount();

A new generation starts when the current one holds more dead members than the scope holds live ones, and at least 64. Existing members never move, so a member that stays mounted does not hold back retirement.

Context functions

All eight are in zgui::prelude.

FunctionWhat it does
provide_context<T: Send + Sync + 'static>(value: T)Makes value visible to every scope below the current one.
use_context<T: Clone + 'static>() -> Option<T>Clones the nearest T. None if nothing above provides one.
expect_context<T: Clone + 'static>() -> TThe same, but panics on a miss. For components that cannot work outside their parent.
with_context<T: 'static, R>(f: impl FnOnce(&T) -> R) -> Option<R>Borrows the nearest T without cloning it.
update_context<T: 'static, R>(f: impl FnOnce(&mut T) -> R) -> Option<R>Mutates the nearest T in place. Notifies nothing.
take_context<T: 'static>() -> Option<T>Removes the nearest T and returns it. The only reader for a T that is not Clone.
provide_local_context<T: 'static>(value: T)Provides a value that is not Send.
use_local_context<T: Clone + 'static>() -> Option<T>Reads a value provided with provide_local_context.

There is no expect_local_context and no take_local_context.

Common mistakes

SymptomCause
expect_context panics naming your typeThe reader is not below the provider.
A lookup returns the wrong valueTwo features use the same type as a key. Use a newtype.
"requires a current owner" panic in debugprovide_context ran outside any component body.
A local context reads as NoneIt was provided with provide_context and read with use_local_context, or the reverse.
"already been disposed" panicA handle outlived the owner that created it.
Nothing updates when the context changesA new value was provided instead of writing a signal inside the existing one.

Next

On this page