Function freya::prelude::use_signal_sync

pub fn use_signal_sync<T>(f: impl FnOnce() -> T) -> Signal<T, SyncStorage>where
    T: Send + Sync + 'static,
Expand description

Creates a new `Send + Sync`` Signal. Signals are a Copy state management solution with automatic dependency tracking.

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

fn App(cx: Scope) -> Element {
    let mut count = use_signal_sync(cx, || 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.
    render! { Child { state: count } }
}

#[component]
fn Child(cx: Scope, state: Signal<u32, SyncStorage>) -> Element {
    let state = *state;

    use_future!(cx,  |()| async move {
        // This signal is Send + Sync, so we can use it in an another thread
        tokio::spawn(async move {
            // Because the signal is a Copy type, we can use it in an async block without cloning it.
            *state.write() += 1;
        }).await;
    });

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