1
0

hooks_bad.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #![allow(non_snake_case)]
  2. use dioxus::prelude::*;
  3. use std::collections::HashMap;
  4. fn main() {
  5. dioxus_desktop::launch(App);
  6. }
  7. fn App(cx: Scope) -> Element {
  8. let you_are_happy = true;
  9. let you_know_it = false;
  10. // ANCHOR: conditional
  11. // ❌ don't call hooks in conditionals!
  12. // We must ensure that the same hooks will be called every time
  13. // But `if` statements only run if the conditional is true!
  14. // So we might violate rule 2.
  15. if you_are_happy && you_know_it {
  16. let something = use_state(cx, || "hands");
  17. println!("clap your {something}")
  18. }
  19. // ✅ instead, *always* call use_state
  20. // You can put other stuff in the conditional though
  21. let something = use_state(cx, || "hands");
  22. if you_are_happy && you_know_it {
  23. println!("clap your {something}")
  24. }
  25. // ANCHOR_END: conditional
  26. // ANCHOR: closure
  27. // ❌ don't call hooks inside closures!
  28. // We can't guarantee that the closure, if used, will be called at the same time every time
  29. let _a = || {
  30. let b = use_state(cx, || 0);
  31. b.get()
  32. };
  33. // ✅ instead, move hook `b` outside
  34. let b = use_state(cx, || 0);
  35. let _a = || b.get();
  36. // ANCHOR_END: closure
  37. let names: Vec<&str> = vec![];
  38. // ANCHOR: loop
  39. // `names` is a Vec<&str>
  40. // ❌ Do not use hooks in loops!
  41. // In this case, if the length of the Vec changes, we break rule 2
  42. for _name in &names {
  43. let is_selected = use_state(cx, || false);
  44. println!("selected: {is_selected}");
  45. }
  46. // ✅ Instead, use a hashmap with use_ref
  47. let selection_map = use_ref(cx, HashMap::<&str, bool>::new);
  48. for name in &names {
  49. let is_selected = selection_map.read()[name];
  50. println!("selected: {is_selected}");
  51. }
  52. // ANCHOR_END: loop
  53. None
  54. }