use_effect.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. use dioxus_core::prelude::*;
  2. use dioxus_signals::ReactiveContext;
  3. /// `use_effect` will subscribe to any changes in the signal values it captures
  4. /// effects will always run after first mount and then whenever the signal values change
  5. /// If the use_effect call was skipped due to an early return, the effect will no longer activate.
  6. /// ```rust
  7. /// fn app() -> Element {
  8. /// let mut count = use_signal(|| 0);
  9. /// //the effect runs again each time count changes
  10. /// use_effect(move || println!("Count changed to {count}"));
  11. ///
  12. /// rsx! {
  13. /// h1 { "High-Five counter: {count}" }
  14. /// button { onclick: move |_| count += 1, "Up high!" }
  15. /// button { onclick: move |_| count -= 1, "Down low!" }
  16. /// }
  17. /// }
  18. /// ```
  19. pub fn use_effect(mut callback: impl FnMut() + 'static) {
  20. // let mut run_effect = use_hook(|| CopyValue::new(true));
  21. // use_hook_did_run(move |did_run| run_effect.set(did_run));
  22. use_hook(|| {
  23. spawn(async move {
  24. let rc = ReactiveContext::new();
  25. loop {
  26. // Wait for the dom the be finished with sync work
  27. flush_sync().await;
  28. // Run the effect
  29. rc.run_in(&mut callback);
  30. // Wait for context to change
  31. rc.changed().await;
  32. }
  33. });
  34. });
  35. }