Function with_context

pub fn with_context<T, R>(cb: impl FnOnce(&T) -> R) -> Option<R>
where T: 'static,
Expand description

Access a reference to a context value of type T in the reactive system.

This traverses the reactive ownership graph, beginning from the current reactive Owner and iterating through its parents, if any. When the value is found, the function that you pass is applied to an immutable reference to it.

The context value should have been provided elsewhere using provide_context.

This is useful for passing values down to components or functions lower in a hierarchy without needs to “prop drill” by passing them through each layer as arguments to a function or properties of a component.

Context works similarly to variable scope: a context that is provided higher in the reactive graph can be used lower down, but a context that is provided lower in the tree cannot be used higher up.

Effect::new(move |_| {
    provide_context(String::from("foo"));

    Effect::new(move |_| {
        let value = with_context::<String, _>(|val| val.to_string())
            .expect("could not find String in context");
        assert_eq!(value, "foo");
    });
});