memo_chain.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. dioxus::launch(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. if depth() > 0 {
  20. Child { depth, items, state }
  21. }
  22. }
  23. }
  24. #[component]
  25. fn Child(state: Memo<isize>, items: Memo<Vec<isize>>, depth: ReadOnlySignal<usize>) -> Element {
  26. // These memos don't get re-computed when early returns happen
  27. let state = use_memo(move || state() + 1);
  28. let item = use_memo(move || items()[depth() - 1]);
  29. let depth = use_memo(move || depth() - 1);
  30. println!("rendering child: {}", depth());
  31. rsx! {
  32. h3 { "Depth({depth})-Item({item}): {state}"}
  33. if depth() > 0 {
  34. Child { depth, state, items }
  35. }
  36. }
  37. }