Function leptos::create_memo
source Β· pub fn create_memo<T>(f: impl Fn(Option<&T>) -> T + 'static) -> Memo<T>where
T: PartialEq + 'static,
Expand description
Creates an efficient derived reactive value based on other reactive values.
Unlike a βderived signal,β a memo comes with two guarantees:
- The memo will only run once per change, no matter how many times you access its value.
- The memo will only notify its dependents if the value of the computation changes.
This makes a memo the perfect tool for expensive computations.
Memos have a certain overhead compared to derived signals. In most cases, you should create a derived signal. But if the derivation calculation is expensive, you should create a memo.
As with create_effect
, the argument to the memo function is the previous value,
i.e., the current value of the memo, which will be None
for the initial calculation.
let (value, set_value) = create_signal(0);
// π we could create a derived signal with a simple function
let double_value = move || value.get() * 2;
set_value.set(2);
assert_eq!(double_value(), 4);
// but imagine the computation is really expensive
let expensive = move || really_expensive_computation(value.get()); // lazy: doesn't run until called
create_effect(move |_| {
// π run #1: calls `really_expensive_computation` the first time
log::debug!("expensive = {}", expensive());
});
create_effect(move |_| {
// β run #2: this calls `really_expensive_computation` a second time!
let value = expensive();
// do something else...
});
// instead, we create a memo
// π run #1: the calculation runs once immediately
let memoized = create_memo(move |_| really_expensive_computation(value.get()));
create_effect(move |_| {
// π reads the current value of the memo
// can be `memoized()` on nightly
log::debug!("memoized = {}", memoized.get());
});
create_effect(move |_| {
// β
reads the current value **without re-running the calculation**
let value = memoized.get();
// do something else...
});