2024-02-14 20:33:07 +00:00
|
|
|
//! This example shows how you can chain memos together to create a tree of memoized values.
|
|
|
|
//!
|
|
|
|
//! Memos will also pause when their parent component pauses, so if you have a memo that depends on a signal, and the
|
|
|
|
//! signal pauses, the memo will pause too.
|
|
|
|
|
2024-01-27 06:33:41 +00:00
|
|
|
use dioxus::prelude::*;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
launch_desktop(app);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn app() -> Element {
|
2024-01-30 01:02:26 +00:00
|
|
|
let mut value = use_signal(|| 0);
|
2024-01-31 02:29:49 +00:00
|
|
|
let mut depth = use_signal(|| 0_usize);
|
2024-01-31 01:59:57 +00:00
|
|
|
let items = use_memo(move || (0..depth()).map(|f| f as _).collect::<Vec<isize>>());
|
2024-01-30 01:02:26 +00:00
|
|
|
let state = use_memo(move || value() + 1);
|
2024-01-27 06:33:41 +00:00
|
|
|
|
|
|
|
println!("rendering app");
|
|
|
|
|
|
|
|
rsx! {
|
2024-01-30 01:02:26 +00:00
|
|
|
button { onclick: move |_| value += 1, "Increment" }
|
2024-01-27 06:33:41 +00:00
|
|
|
button { onclick: move |_| depth += 1, "Add depth" }
|
|
|
|
button { onclick: move |_| depth -= 1, "Remove depth" }
|
2024-01-30 01:02:26 +00:00
|
|
|
Child { depth, items, state }
|
2024-01-27 06:33:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[component]
|
|
|
|
fn Child(
|
|
|
|
state: ReadOnlySignal<isize>,
|
|
|
|
items: ReadOnlySignal<Vec<isize>>,
|
|
|
|
depth: ReadOnlySignal<usize>,
|
|
|
|
) -> Element {
|
|
|
|
if depth() == 0 {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2024-01-27 07:05:40 +00:00
|
|
|
// These memos don't get re-computed when early returns happen
|
2024-01-27 06:33:41 +00:00
|
|
|
let state = use_memo(move || state() + 1);
|
2024-01-28 10:21:05 +00:00
|
|
|
let item = use_memo(move || items()[depth()]);
|
2024-01-27 06:33:41 +00:00
|
|
|
let depth = use_memo(move || depth() - 1);
|
|
|
|
|
2024-01-28 10:21:05 +00:00
|
|
|
println!("rendering child: {}", depth());
|
|
|
|
|
2024-01-27 06:33:41 +00:00
|
|
|
rsx! {
|
|
|
|
h3 { "Depth({depth})-Item({item}): {state}"}
|
2024-01-30 01:02:26 +00:00
|
|
|
Child { depth, state, items }
|
2024-01-27 06:33:41 +00:00
|
|
|
}
|
|
|
|
}
|