Function leptos::use_context

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

Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. 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.

use leptos::*;

// define a newtype we'll provide as context
// contexts are stored by their types, so it can be useful to create
// a new type to avoid confusion with other `WriteSignal<i32>`s we may have
// all types to be shared via context should implement `Clone`
#[derive(Copy, Clone)]
struct ValueSetter(WriteSignal<i32>);

#[component]
pub fn Provider() -> impl IntoView {
    let (value, set_value) = create_signal(0);

    // the newtype pattern isn't *necessary* here but is a good practice
    // it avoids confusion with other possible future `WriteSignal<bool>` contexts
    // and makes it easier to refer to it in ButtonD
    provide_context(ValueSetter(set_value));

    // because <Consumer/> is nested inside <Provider/>,
    // it has access to the provided context
    view! { <div><Consumer/></div> }
}

#[component]
pub fn Consumer() -> impl IntoView {
    // consume the provided context of type `ValueSetter` using `use_context`
    // this traverses up the reactive graph and gets the nearest provided `ValueSetter`
    let set_value = use_context::<ValueSetter>().unwrap().0;

}