Function take_context
pub fn take_context<T>() -> Option<T>where
T: 'static,
Expand description
Extracts a context value of type T
from the reactive system, and takes ownership,
removing it from the context 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 removed,
and is not available to any other use_context
or take_context
calls.
If the value is Clone
, use use_context
instead.
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.
#[derive(Debug, PartialEq)]
struct NotClone(String);
Effect::new(move |_| {
provide_context(NotClone(String::from("foo")));
Effect::new(move |_| {
// take_context removes the value from context without needing to clone
let value = take_context::<NotClone>();
assert_eq!(value, Some(NotClone(String::from("foo"))));
let value2 = take_context::<NotClone>();
assert_eq!(value2, None);
});
});