usestate.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #![warn(clippy::pedantic)]
  2. use dioxus_core::prelude::*;
  3. use std::{
  4. cell::{RefCell, RefMut},
  5. fmt::{Debug, Display},
  6. rc::Rc,
  7. };
  8. /// Store state between component renders.
  9. ///
  10. /// ## Dioxus equivalent of useState, designed for Rust
  11. ///
  12. /// The Dioxus version of `useState` for state management inside components. It allows you to ergonomically store and
  13. /// modify state between component renders. When the state is updated, the component will re-render.
  14. ///
  15. ///
  16. /// ```ignore
  17. /// const Example: Component = |cx| {
  18. /// let (count, set_count) = use_state(&cx, || 0);
  19. ///
  20. /// cx.render(rsx! {
  21. /// div {
  22. /// h1 { "Count: {count}" }
  23. /// button { onclick: move |_| set_count(a - 1), "Increment" }
  24. /// button { onclick: move |_| set_count(a + 1), "Decrement" }
  25. /// }
  26. /// ))
  27. /// }
  28. /// ```
  29. pub fn use_state<'a, T: 'static>(
  30. cx: &'a ScopeState,
  31. initial_state_fn: impl FnOnce() -> T,
  32. ) -> (&'a T, &'a UseState<T>) {
  33. let hook = cx.use_hook(move |_| {
  34. let current_val = Rc::new(initial_state_fn());
  35. let update_callback = cx.schedule_update();
  36. let slot = Rc::new(RefCell::new(current_val.clone()));
  37. let setter = Rc::new({
  38. crate::to_owned![update_callback, slot];
  39. move |new| {
  40. let mut slot = slot.borrow_mut();
  41. // if there's only one reference (weak or otherwise), we can just swap the values
  42. // Typically happens when the state is set multiple times - we don't want to create a new Rc for each new value
  43. if let Some(val) = Rc::get_mut(&mut slot) {
  44. *val = new;
  45. } else {
  46. *slot = Rc::new(new);
  47. }
  48. update_callback();
  49. }
  50. });
  51. UseState {
  52. current_val,
  53. update_callback,
  54. setter,
  55. slot,
  56. }
  57. });
  58. (hook.current_val.as_ref(), hook)
  59. }
  60. pub struct UseState<T: 'static> {
  61. pub(crate) current_val: Rc<T>,
  62. pub(crate) update_callback: Rc<dyn Fn()>,
  63. pub(crate) setter: Rc<dyn Fn(T)>,
  64. pub(crate) slot: Rc<RefCell<Rc<T>>>,
  65. }
  66. impl<T: 'static> UseState<T> {
  67. /// Get the current value of the state by cloning its container Rc.
  68. ///
  69. /// This is useful when you are dealing with state in async contexts but need
  70. /// to know the current value. You are not given a reference to the state.
  71. ///
  72. /// # Examples
  73. /// An async context might need to know the current value:
  74. ///
  75. /// ```rust, ignore
  76. /// fn component(cx: Scope) -> Element {
  77. /// let (count, set_count) = use_state(&cx, || 0);
  78. /// cx.spawn({
  79. /// let set_count = set_count.to_owned();
  80. /// async move {
  81. /// let current = set_count.current();
  82. /// }
  83. /// })
  84. /// }
  85. /// ```
  86. #[must_use]
  87. pub fn current(&self) -> Rc<T> {
  88. self.slot.borrow().clone()
  89. }
  90. /// Get the `setter` function directly without the `UseState` wrapper.
  91. ///
  92. /// This is useful for passing the setter function to other components.
  93. ///
  94. /// However, for most cases, calling `to_owned` o`UseState`te is the
  95. /// preferred way to get "anoth`set_state`tate handle.
  96. ///
  97. ///
  98. /// # Examples
  99. /// A component might require an `Rc<dyn Fn(T)>` as an input to set a value.
  100. ///
  101. /// ```rust, ignore
  102. /// fn component(cx: Scope) -> Element {
  103. /// let (value, set_value) = use_state(&cx, || 0);
  104. ///
  105. /// rsx!{
  106. /// Component {
  107. /// handler: set_val.setter()
  108. /// }
  109. /// }
  110. /// }
  111. /// ```
  112. #[must_use]
  113. pub fn setter(&self) -> Rc<dyn Fn(T)> {
  114. self.setter.clone()
  115. }
  116. /// Set the state to a new value, using the current state value as a reference.
  117. ///
  118. /// This is similar to passing a closure to React's `set_value` function.
  119. ///
  120. /// # Examples
  121. ///
  122. /// Basic usage:
  123. /// ```rust
  124. /// # use dioxus_core::prelude::*;
  125. /// # use dioxus_hooks::*;
  126. /// fn component(cx: Scope) -> Element {
  127. /// let (value, set_value) = use_state(&cx, || 0);
  128. ///
  129. /// // to increment the value
  130. /// set_value.modify(|v| v + 1);
  131. ///
  132. /// // usage in async
  133. /// cx.spawn({
  134. /// let set_value = set_value.to_owned();
  135. /// async move {
  136. /// set_value.modify(|v| v + 1);
  137. /// }
  138. /// });
  139. ///
  140. /// # todo!()
  141. /// }
  142. /// ```
  143. pub fn modify(&self, f: impl FnOnce(&T) -> T) {
  144. let curernt = self.slot.borrow();
  145. let new_val = f(curernt.as_ref());
  146. (self.setter)(new_val);
  147. }
  148. /// Get the value of the state when this handle was created.
  149. ///
  150. /// This method is useful when you want an `Rc` around the data to cheaply
  151. /// pass it around your app.
  152. ///
  153. /// ## Warning
  154. ///
  155. /// This will return a stale value if used within async contexts.
  156. ///
  157. /// Try `current` to get the real current value of the state.
  158. ///
  159. /// ## Example
  160. ///
  161. /// ```rust, ignore
  162. /// # use dioxus_core::prelude::*;
  163. /// # use dioxus_hooks::*;
  164. /// fn component(cx: Scope) -> Element {
  165. /// let (value, set_value) = use_state(&cx, || 0);
  166. ///
  167. /// let as_rc = set_value.get();
  168. /// assert_eq!(as_rc.as_ref(), &0);
  169. ///
  170. /// # todo!()
  171. /// }
  172. /// ```
  173. #[must_use]
  174. pub fn get(&self) -> &Rc<T> {
  175. &self.current_val
  176. }
  177. /// Mark the component that create this [`UseState`] as dirty, forcing it to re-render.
  178. ///
  179. /// ```rust, ignore
  180. /// fn component(cx: Scope) -> Element {
  181. /// let (count, set_count) = use_state(&cx, || 0);
  182. /// cx.spawn({
  183. /// let set_count = set_count.to_owned();
  184. /// async move {
  185. /// // for the component to re-render
  186. /// set_count.needs_update();
  187. /// }
  188. /// })
  189. /// }
  190. /// ```
  191. pub fn needs_update(&self) {
  192. (self.update_callback)();
  193. }
  194. }
  195. impl<T: Clone> UseState<T> {
  196. /// Get a mutable handle to the value by calling `ToOwned::to_owned` on the
  197. /// current value.
  198. ///
  199. /// This is essentially cloning the underlying value and then setting it,
  200. /// giving you a mutable handle in the process. This method is intended for
  201. /// types that are cheaply cloneable.
  202. ///
  203. /// If you are comfortable dealing with `RefMut`, then you can use `make_mut` to get
  204. /// the underlying slot. However, be careful with `RefMut` since you might panic
  205. /// if the `RefCell` is left open.
  206. ///
  207. /// # Examples
  208. ///
  209. /// ```
  210. /// let (val, set_val) = use_state(&cx, || 0);
  211. ///
  212. /// set_val.with_mut(|v| *v = 1);
  213. /// ```
  214. pub fn with_mut(&self, apply: impl FnOnce(&mut T)) {
  215. let mut slot = self.slot.borrow_mut();
  216. let mut inner = slot.as_ref().to_owned();
  217. apply(&mut inner);
  218. if let Some(new) = Rc::get_mut(&mut slot) {
  219. *new = inner;
  220. } else {
  221. *slot = Rc::new(inner);
  222. }
  223. self.needs_update();
  224. }
  225. /// Get a mutable handle to the value by calling `ToOwned::to_owned` on the
  226. /// current value.
  227. ///
  228. /// This is essentially cloning the underlying value and then setting it,
  229. /// giving you a mutable handle in the process. This method is intended for
  230. /// types that are cheaply cloneable.
  231. ///
  232. /// # Warning
  233. /// Be careful with `RefMut` since you might panic if the `RefCell` is left open!
  234. ///
  235. /// # Examples
  236. ///
  237. /// ```
  238. /// let (val, set_val) = use_state(&cx, || 0);
  239. ///
  240. /// set_val.with_mut(|v| *v = 1);
  241. /// ```
  242. #[must_use]
  243. pub fn make_mut(&self) -> RefMut<T> {
  244. let mut slot = self.slot.borrow_mut();
  245. self.needs_update();
  246. if Rc::strong_count(&*slot) > 0 {
  247. *slot = Rc::new(slot.as_ref().to_owned());
  248. }
  249. RefMut::map(slot, |rc| Rc::get_mut(rc).expect("the hard count to be 0"))
  250. }
  251. }
  252. impl<T: 'static> ToOwned for UseState<T> {
  253. type Owned = UseState<T>;
  254. fn to_owned(&self) -> Self::Owned {
  255. UseState {
  256. current_val: self.current_val.clone(),
  257. update_callback: self.update_callback.clone(),
  258. setter: self.setter.clone(),
  259. slot: self.slot.clone(),
  260. }
  261. }
  262. }
  263. impl<'a, T: 'static + Display> std::fmt::Display for UseState<T> {
  264. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  265. write!(f, "{}", self.current_val)
  266. }
  267. }
  268. impl<T> PartialEq<UseState<T>> for UseState<T> {
  269. fn eq(&self, other: &UseState<T>) -> bool {
  270. // some level of memoization for UseState
  271. Rc::ptr_eq(&self.slot, &other.slot)
  272. }
  273. }
  274. impl<T: Debug> Debug for UseState<T> {
  275. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  276. write!(f, "{:?}", self.current_val)
  277. }
  278. }
  279. impl<'a, T> std::ops::Deref for UseState<T> {
  280. type Target = Rc<dyn Fn(T)>;
  281. fn deref(&self) -> &Self::Target {
  282. &self.setter
  283. }
  284. }
  285. #[test]
  286. fn api_makes_sense() {
  287. #[allow(unused)]
  288. fn app(cx: Scope) -> Element {
  289. let (val, set_val) = use_state(&cx, || 0);
  290. set_val(0);
  291. set_val.modify(|v| v + 1);
  292. let real_current = set_val.current();
  293. match val {
  294. 10 => {
  295. set_val(20);
  296. set_val.modify(|v| v + 1);
  297. }
  298. 20 => {}
  299. _ => {
  300. println!("{real_current}");
  301. }
  302. }
  303. cx.spawn({
  304. crate::to_owned![set_val];
  305. async move {
  306. set_val.modify(|f| f + 1);
  307. }
  308. });
  309. cx.render(LazyNodes::new(|f| f.static_text("asd")))
  310. }
  311. }