usestate.rs 9.8 KB

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