1
0

backgrounded_futures.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //! Backgrounded futures example
  2. //!
  3. //! This showcases how use_future, use_memo, and use_effect will stop running if the component returns early.
  4. //! Generally you should avoid using early returns around hooks since most hooks are not properly designed to
  5. //! handle early returns. However, use_future *does* pause the future when the component returns early, and so
  6. //! hooks that build on top of it like use_memo and use_effect will also pause.
  7. //!
  8. //! This example is more of a demonstration of the behavior than a practical use case, but it's still interesting to see.
  9. use async_std::task::sleep;
  10. use dioxus::prelude::*;
  11. fn main() {
  12. dioxus::launch(app);
  13. }
  14. fn app() -> Element {
  15. let mut show_child = use_signal(|| true);
  16. let mut count = use_signal(|| 0);
  17. let child = use_memo(move || {
  18. rsx! {
  19. Child { count }
  20. }
  21. });
  22. rsx! {
  23. // Some toggle/controls to show the child or increment the count
  24. button { onclick: move |_| show_child.toggle(), "Toggle child" }
  25. button { onclick: move |_| count += 1, "Increment count" }
  26. if show_child() {
  27. {child()}
  28. }
  29. }
  30. }
  31. #[component]
  32. fn Child(count: Signal<i32>) -> Element {
  33. let mut early_return = use_signal(|| false);
  34. let early = rsx! {
  35. button { onclick: move |_| early_return.toggle(), "Toggle {early_return} early return" }
  36. };
  37. if early_return() {
  38. return early;
  39. }
  40. use_future(move || async move {
  41. loop {
  42. sleep(std::time::Duration::from_millis(100)).await;
  43. println!("Child")
  44. }
  45. });
  46. use_effect(move || println!("Child count: {}", count()));
  47. rsx! {
  48. div {
  49. "Child component"
  50. {early}
  51. }
  52. }
  53. }