1
0

hooks_custom_logic.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #![allow(unused)]
  2. use dioxus::prelude::*;
  3. fn main() {}
  4. // ANCHOR: use_state
  5. use std::cell::RefCell;
  6. use std::rc::Rc;
  7. use std::sync::Arc;
  8. #[derive(Clone)]
  9. struct UseState<T> {
  10. value: Rc<RefCell<T>>,
  11. update: Arc<dyn Fn()>,
  12. }
  13. fn my_use_state<T: 'static>(cx: &ScopeState, init: impl FnOnce() -> T) -> &UseState<T> {
  14. cx.use_hook(|| {
  15. // The update function will trigger a re-render in the component cx is attached to
  16. let update = cx.schedule_update();
  17. // Create the initial state
  18. let value = Rc::new(RefCell::new(init()));
  19. UseState { value, update }
  20. })
  21. }
  22. impl<T: Clone> UseState<T> {
  23. fn get(&self) -> T {
  24. self.value.borrow().clone()
  25. }
  26. fn set(&self, value: T) {
  27. // Update the state
  28. *self.value.borrow_mut() = value;
  29. // Trigger a re-render on the component the state is from
  30. (self.update)();
  31. }
  32. }
  33. // ANCHOR_END: use_state
  34. // ANCHOR: use_context
  35. pub fn use_context<T: 'static + Clone>(cx: &ScopeState) -> Option<&T> {
  36. cx.use_hook(|| cx.consume_context::<T>()).as_ref()
  37. }
  38. pub fn use_context_provider<T: 'static + Clone>(cx: &ScopeState, f: impl FnOnce() -> T) -> &T {
  39. cx.use_hook(|| {
  40. let val = f();
  41. // Provide the context state to the scope
  42. cx.provide_context(val.clone());
  43. val
  44. })
  45. }
  46. // ANCHOR_END: use_context