usestate.rs 9.7 KB

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