Function freya::prelude::use_signal

pub fn use_signal<T>(f: impl FnOnce() -> T) -> Signal<T>where
    T: 'static,
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 {
    let state = *state;

    use_future( |()| 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}"
        }
    }
}