Function dioxus_hooks::use_signal

source ·
pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage>
Expand description

Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.

use dioxus::prelude::*;
use dioxus_signals::*;

fn App() -> Element {
    let mut count = use_signal(|| 0);

    // Because signals have automatic dependency tracking, if you never read them in a component, that component will not be re-rended when the signal is updated.
    // The app component will never be rerendered in this example.
    rsx! { Child { state: count } }
}

#[component]
fn Child(state: Signal<u32>) -> Element {
    use_future(move || async move {
        // Because the signal is a Copy type, we can use it in an async block without cloning it.
        *state.write() += 1;
    });

    rsx! {
        button {
            onclick: move |_| *state.write() += 1,
            "{state}"
        }
    }
}