pub fn use_shared_state<T: 'static>(
    cx: &ScopeState
) -> Option<&UseSharedState<T>>
Expand description

This hook provides some relatively light ergonomics around shared state.

It is not a substitute for a proper state management system, but it is capable enough to provide use_state - type ergonomics in a pinch, with zero cost.

Example


#[derive(Clone, Copy)]
enum Theme {
    Light,
    Dark,
}

// Provider
fn Parent<'a>(cx: Scope<'a>) -> Element<'a> {
    use_shared_state_provider(cx, || Theme::Dark);
    let theme = use_shared_state::<Theme>(cx).unwrap();

    render! {
        button{
            onclick: move |_| {
                let current_theme = *theme.read();
                *theme.write() = match current_theme {
                    Theme::Dark => Theme::Light,
                    Theme::Light => Theme::Dark,
                };
            },
            "Change theme"
        }
        Child{}
    }
}

// Consumer
fn Child<'a>(cx: Scope<'a>) -> Element<'a> {
    let theme = use_shared_state::<Theme>(cx).unwrap();
    let current_theme = *theme.read();

    render! {
        match &*theme.read() {
            Theme::Dark => {
                "Dark mode"
            }
            Theme::Light => {
                "Light mode"
            }
        }
    }
}

How it works

Any time a component calls write, every consumer of the state will be notified - excluding the provider.

Right now, there is not a distinction between read-only and write-only, so every consumer will be notified.