Skip to main content

use_context

Function use_context 

Source
pub fn use_context<T>() -> Option<T>
where T: Clone + 'static,
Expand description

The reactive-programming vocabulary Component state is built on: signals, memos, and context, flat-re-exported from frust-reactive/ reactive_graph so app authors never name either crate directly. Extracts a context value of type T from 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, it is cloned.

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.

While the term “consume” is sometimes used, note that use_context clones the value, rather than removing it; it is still accessible to other users.

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

    Effect::new(move |_| {
        // each use_context clones the value
        let value = use_context::<String>()
            .expect("could not find String in context");
        assert_eq!(value, "foo");
        let value2 = use_context::<String>()
            .expect("could not find String in context");
        assert_eq!(value2, "foo");
    });
});