sycamore::reactive

Function create_memo

pub fn create_memo<T>(f: impl FnMut() -> T + 'static) -> ReadSignal<T>
Expand description

Creates a memoized computation from some signals.

The output is derived from all the signals that are used within the memo closure. If any of the tracked signals are updated, the memo is also updated.

§Difference from derived signals

Derived signals (functions referencing signals) are lazy and do not keep track of the result of the computation. This means that the computation will not be executed until needed. This also means that calling the derived signal twice will result in the same computation twice.

let state = create_signal(0);
let double = || state.get() * 2;

let _ = double();
// Here, the closure named double is called again.
// If the computation is expensive enough, this would be wasted work!
let _ = double();

Memos, on the other hand, are eagerly evaluated and will only run the computation when one of its dependencies change.

Memos also incur a slightly higher performance penalty than simple derived signals, so unless there is some computation involved, it will likely be faster to just use a derived signal.

§Example

let state = create_signal(0);
let double = create_memo(move || state.get() * 2);

assert_eq!(double.get(), 0);
state.set(1);
assert_eq!(double.get(), 2);