provide_context

Function provide_context 

Source
pub fn provide_context<T, I, F, R>(init: I, f: F) -> R
where T: Send + Sync + 'static, I: FnOnce() -> T, F: FnOnce() -> R,
Expand description

Provides a typed context value for the duration of the given closure.

The init closure is evaluated only when the context slot is created (or re-created after being recycled).

This is intended for use inside component build functions only.

ยงExamples

use tessera_ui::{Color, provide_context, tessera, use_context};

#[derive(Default)]
struct Theme {
    primary: Color,
}

#[tessera]
fn root() {
    provide_context(
        || Theme {
            primary: Color::RED,
        },
        || {
            leaf();
        },
    );
}

#[tessera]
fn leaf() {
    let theme = use_context::<Theme>().expect("Theme must be provided");
    theme.with(|t| assert_eq!(t.primary, Color::RED));
}