pub fn create_memo<'a, U: 'a>(
    cx: Scope<'a>,
    f: impl FnMut() -> U + 'a
) -> &'a ReadSignal<U>
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(cx, 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.

Example

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

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