1
0

hooks_anti_patterns.rs 895 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #![allow(unused)]
  2. use dioxus::prelude::*;
  3. fn main() {}
  4. // ANCHOR: non_clone_state
  5. use std::cell::RefCell;
  6. use std::rc::Rc;
  7. use std::sync::Arc;
  8. struct UseState<'a, T> {
  9. value: &'a RefCell<T>,
  10. update: Arc<dyn Fn()>,
  11. }
  12. fn my_use_state<T: 'static>(cx: &ScopeState, init: impl FnOnce() -> T) -> UseState<T> {
  13. // The update function will trigger a re-render in the component cx is attached to
  14. let update = cx.schedule_update();
  15. // Create the initial state
  16. let value = cx.use_hook(|| RefCell::new(init()));
  17. UseState { value, update }
  18. }
  19. impl<T: Clone> UseState<'_, T> {
  20. fn get(&self) -> T {
  21. self.value.borrow().clone()
  22. }
  23. fn set(&self, value: T) {
  24. // Update the state
  25. *self.value.borrow_mut() = value;
  26. // Trigger a re-render on the component the state is from
  27. (self.update)();
  28. }
  29. }
  30. // ANCHOR_END: non_clone_state