leptos::reactive::signal

Function signal

Source
pub fn signal<T>(value: T) -> (ReadSignal<T>, WriteSignal<T>)
where T: Send + Sync + 'static,
Expand description

Creates an arena-allocated signal, the basic reactive primitive.

A signal is a piece of data that may change over time, and notifies other code when it has changed. This is the atomic unit of reactivity, which begins all other processes of updating.

Takes the initial value as an argument, and returns a tuple containing a ReadSignal and a WriteSignal.

This returns an arena-allocated signal, which is Copy and is disposed when its reactive Owner cleans up. For a reference-counted signal that lives as long as a reference to it is alive, see arc_signal.

let (count, set_count) = signal(0);

// ✅ calling the getter clones and returns the value
//    this can be `count()` on nightly
assert_eq!(count.get(), 0);

// ✅ calling the setter sets the value
//    this can be `set_count(1)` on nightly
set_count.set(1);
assert_eq!(count.get(), 1);

// ❌ you could call the getter within the setter
// set_count.set(count.get() + 1);

// ✅ however it's more efficient to use .update() and mutate the value in place
set_count.update(|count: &mut i32| *count += 1);
assert_eq!(count.get(), 2);

// ✅ you can create "derived signals" with a Fn() -> T interface
let double_count = move || count.get() * 2; // signals are `Copy` so you can `move` them anywhere
set_count.set(0);
assert_eq!(double_count(), 0);
set_count.set(1);
assert_eq!(double_count(), 2);