Function update_context

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

Update 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 a mutable 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 = update_context::<String, _>(|val| {
            std::mem::replace(val, "bar".to_string())
        })
        .expect("could not find String in context");
        assert_eq!(value, "foo");
        assert_eq!(expect_context::<String>(), "bar");
    });
});