Function provide_context
pub fn provide_context<T>(value: T)
Expand description
Provides a context value of type T
to the current reactive Owner
and all of its descendants. This can be accessed using use_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 down cannot be used higher up.
Effect::new(move |_| {
println!("Provider");
provide_context(42i32); // provide an i32
Effect::new(move |_| {
println!("intermediate node");
Effect::new(move |_| {
let value = use_context::<i32>()
.expect("could not find i32 in context");
assert_eq!(value, 42);
});
});
});
§Context Shadowing
Only a single value of any type can be provided via context. If you need to provide multiple values of the same type, wrap each one in a “newtype” struct wrapper so that each one is a distinct type.
Providing a second value of the same type “lower” in the ownership tree will shadow the value,
just as a second let
declaration with the same variable name will shadow that variable.
Effect::new(move |_| {
println!("Provider");
provide_context("foo"); // provide a &'static str
Effect::new(move |_| {
// before we provide another value of the same type, we can access the old one
assert_eq!(use_context::<&'static str>(), Some("foo"));
// but providing another value of the same type shadows it
provide_context("bar");
Effect::new(move |_| {
assert_eq!(use_context::<&'static str>(), Some("bar"));
});
});
});