memo_chain.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //! This example shows how you can chain memos together to create a tree of memoized values.
  2. //!
  3. //! Memos will also pause when their parent component pauses, so if you have a memo that depends on a signal, and the
  4. //! signal pauses, the memo will pause too.
  5. use dioxus::prelude::*;
  6. fn main() {
  7. launch_desktop(app);
  8. }
  9. fn app() -> Element {
  10. let mut value = use_signal(|| 0);
  11. let mut depth = use_signal(|| 0_usize);
  12. let items = use_memo(move || (0..depth()).map(|f| f as _).collect::<Vec<isize>>());
  13. let state = use_memo(move || value() + 1);
  14. println!("rendering app");
  15. rsx! {
  16. button { onclick: move |_| value += 1, "Increment" }
  17. button { onclick: move |_| depth += 1, "Add depth" }
  18. button { onclick: move |_| depth -= 1, "Remove depth" }
  19. Child { depth, items, state }
  20. }
  21. }
  22. #[component]
  23. fn Child(
  24. state: ReadOnlySignal<isize>,
  25. items: ReadOnlySignal<Vec<isize>>,
  26. depth: ReadOnlySignal<usize>,
  27. ) -> Element {
  28. if depth() == 0 {
  29. return None;
  30. }
  31. // These memos don't get re-computed when early returns happen
  32. let state = use_memo(move || state() + 1);
  33. let item = use_memo(move || items()[depth()]);
  34. let depth = use_memo(move || depth() - 1);
  35. println!("rendering child: {}", depth());
  36. rsx! {
  37. h3 { "Depth({depth})-Item({item}): {state}"}
  38. Child { depth, state, items }
  39. }
  40. }