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}")}}
}
}
}Appprovides in its own body, so its own view can read the context too.- The context values are
Copybecause they hold signal handles, not data.use_contextclones, 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_contextpanics 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 reasonwith_context,update_contextandtake_contextcannot see a local context. Read it only withuse_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 owner | Example |
|---|---|
| arena-backed handles | RwSignal, ReadSignal, WriteSignal, Memo, Signal, Store |
| stored values | StoredValue |
| contexts | values passed to provide_context |
| cleanups | closures passed to on_cleanup_local |
| child owners | one 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
RenderEffectlives 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:
| Owner | Created by | Disposed of when |
|---|---|---|
| application | the runtime, above every window | the application ends |
| window | the runtime, once per open window | the window closes, or the platform suspends it |
| component | #[component], around each call | the component is unmounted; it is also cleaned before its body re-runs on a rebuild |
| list row | for / For | that row's key leaves the collection |
| branch | if / Show | the 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:
- Its child owners are disposed of, depth first.
- Its cleanups run, in the order they were registered.
- 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 processFour operations check for an owner, and panic in debug builds when there is none (the check compiles away in release):
provide_contextprovide_local_contexton_cleanup_localSelector::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):
| Limit | Logged when |
|---|---|
| owner depth 4096 | one owner chain is deeper than this: owners are nested and never disposed of |
| 1024 children | one 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 panicsMounted::new()with no current owner creates a root. Inside another scope'swith, 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 callunmountexplicitly. - 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.
| Function | What 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>() -> T | The 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
| Symptom | Cause |
|---|---|
expect_context panics naming your type | The reader is not below the provider. |
| A lookup returns the wrong value | Two features use the same type as a key. Use a newtype. |
| "requires a current owner" panic in debug | provide_context ran outside any component body. |
A local context reads as None | It was provided with provide_context and read with use_local_context, or the reverse. |
| "already been disposed" panic | A handle outlived the owner that created it. |
| Nothing updates when the context changes | A new value was provided instead of writing a signal inside the existing one. |
Next
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.
Stores and selectors
Per-field subscriptions for struct-shaped state, keyed collections, and a selector that updates two rows instead of all of them.