scopes.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. use crate::{
  2. any_props::AnyProps,
  3. any_props::VProps,
  4. bump_frame::BumpFrame,
  5. innerlude::{DynamicNode, EventHandler, VComponent, VText},
  6. innerlude::{ErrorBoundary, Scheduler, SchedulerMsg},
  7. lazynodes::LazyNodes,
  8. nodes::{IntoAttributeValue, IntoDynNode, RenderReturn},
  9. AnyValue, Attribute, AttributeValue, Element, Event, Properties, TaskId,
  10. };
  11. use bumpalo::{boxed::Box as BumpBox, Bump};
  12. use rustc_hash::FxHashSet;
  13. use std::{
  14. any::{Any, TypeId},
  15. cell::{Cell, RefCell, UnsafeCell},
  16. fmt::{Arguments, Debug},
  17. future::Future,
  18. rc::Rc,
  19. sync::Arc,
  20. };
  21. /// A wrapper around the [`Scoped`] object that contains a reference to the [`ScopeState`] and properties for a given
  22. /// component.
  23. ///
  24. /// The [`Scope`] is your handle to the [`crate::VirtualDom`] and the component state. Every component is given its own
  25. /// [`ScopeState`] and merged with its properties to create a [`Scoped`].
  26. ///
  27. /// The [`Scope`] handle specifically exists to provide a stable reference to these items for the lifetime of the
  28. /// component render.
  29. pub type Scope<'a, T = ()> = &'a Scoped<'a, T>;
  30. // This ScopedType exists because we want to limit the amount of monomorphization that occurs when making inner
  31. // state type generic over props. When the state is generic, it causes every method to be monomorphized for every
  32. // instance of Scope<T> in the codebase.
  33. //
  34. //
  35. /// A wrapper around a component's [`ScopeState`] and properties. The [`ScopeState`] provides the majority of methods
  36. /// for the VirtualDom and component state.
  37. pub struct Scoped<'a, T = ()> {
  38. /// The component's state and handle to the scheduler.
  39. ///
  40. /// Stores things like the custom bump arena, spawn functions, hooks, and the scheduler.
  41. pub scope: &'a ScopeState,
  42. /// The component's properties.
  43. pub props: &'a T,
  44. }
  45. impl<'a, T> std::ops::Deref for Scoped<'a, T> {
  46. type Target = &'a ScopeState;
  47. fn deref(&self) -> &Self::Target {
  48. &self.scope
  49. }
  50. }
  51. /// A component's unique identifier.
  52. ///
  53. /// `ScopeId` is a `usize` that acts a key for the internal slab of Scopes. This means that the key is not unqiue across
  54. /// time. We do try and guarantee that between calls to `wait_for_work`, no ScopeIds will be recycled in order to give
  55. /// time for any logic that relies on these IDs to properly update.
  56. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  57. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
  58. pub struct ScopeId(pub usize);
  59. /// A component's state separate from its props.
  60. ///
  61. /// This struct exists to provide a common interface for all scopes without relying on generics.
  62. pub struct ScopeState {
  63. pub(crate) render_cnt: Cell<usize>,
  64. pub(crate) name: &'static str,
  65. pub(crate) node_arena_1: BumpFrame,
  66. pub(crate) node_arena_2: BumpFrame,
  67. pub(crate) parent: Option<*const ScopeState>,
  68. pub(crate) id: ScopeId,
  69. pub(crate) height: u32,
  70. pub(crate) suspended: Cell<bool>,
  71. pub(crate) hooks: RefCell<Vec<Box<UnsafeCell<dyn Any>>>>,
  72. pub(crate) hook_idx: Cell<usize>,
  73. pub(crate) shared_contexts: RefCell<Vec<(TypeId, Box<dyn Any>)>>,
  74. pub(crate) tasks: Rc<Scheduler>,
  75. pub(crate) spawned_tasks: RefCell<FxHashSet<TaskId>>,
  76. pub(crate) borrowed_props: RefCell<Vec<*const VComponent<'static>>>,
  77. pub(crate) attributes_to_drop: RefCell<Vec<*const Attribute<'static>>>,
  78. pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
  79. }
  80. impl<'src> ScopeState {
  81. pub(crate) fn current_frame(&self) -> &BumpFrame {
  82. match self.render_cnt.get() % 2 {
  83. 0 => &self.node_arena_1,
  84. 1 => &self.node_arena_2,
  85. _ => unreachable!(),
  86. }
  87. }
  88. pub(crate) fn previous_frame(&self) -> &BumpFrame {
  89. match self.render_cnt.get() % 2 {
  90. 1 => &self.node_arena_1,
  91. 0 => &self.node_arena_2,
  92. _ => unreachable!(),
  93. }
  94. }
  95. /// Get the name of this component
  96. pub fn name(&self) -> &str {
  97. self.name
  98. }
  99. /// Get the current render since the inception of this component
  100. ///
  101. /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
  102. pub fn generation(&self) -> usize {
  103. self.render_cnt.get()
  104. }
  105. /// Get a handle to the currently active bump arena for this Scope
  106. ///
  107. /// This is a bump memory allocator. Be careful using this directly since the contents will be wiped on the next render.
  108. /// It's easy to leak memory here since the drop implementation will not be called for any objects allocated in this arena.
  109. ///
  110. /// If you need to allocate items that need to be dropped, use bumpalo's box.
  111. pub fn bump(&self) -> &Bump {
  112. // note that this is actually the previous frame since we use that as scratch space while the component is rendering
  113. self.previous_frame().bump()
  114. }
  115. /// Get a handle to the currently active head node arena for this Scope
  116. ///
  117. /// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.
  118. ///
  119. /// Panics if the tree has not been built yet.
  120. pub fn root_node(&self) -> &RenderReturn {
  121. self.try_root_node()
  122. .expect("The tree has not been built yet. Make sure to call rebuild on the tree before accessing its nodes.")
  123. }
  124. /// Try to get a handle to the currently active head node arena for this Scope
  125. ///
  126. /// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.
  127. ///
  128. /// Returns [`None`] if the tree has not been built yet.
  129. pub fn try_root_node(&self) -> Option<&RenderReturn> {
  130. let ptr = self.current_frame().node.get();
  131. if ptr.is_null() {
  132. return None;
  133. }
  134. let r: &RenderReturn = unsafe { &*ptr };
  135. unsafe { std::mem::transmute(r) }
  136. }
  137. /// Get the height of this Scope - IE the number of scopes above it.
  138. ///
  139. /// A Scope with a height of `0` is the root scope - there are no other scopes above it.
  140. ///
  141. /// # Example
  142. ///
  143. /// ```rust, ignore
  144. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  145. /// dom.rebuild();
  146. ///
  147. /// let base = dom.base_scope();
  148. ///
  149. /// assert_eq!(base.height(), 0);
  150. /// ```
  151. pub fn height(&self) -> u32 {
  152. self.height
  153. }
  154. /// Get the Parent of this [`Scope`] within this Dioxus [`crate::VirtualDom`].
  155. ///
  156. /// This ID is not unique across Dioxus [`crate::VirtualDom`]s or across time. IDs will be reused when components are unmounted.
  157. ///
  158. /// The base component will not have a parent, and will return `None`.
  159. ///
  160. /// # Example
  161. ///
  162. /// ```rust, ignore
  163. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  164. /// dom.rebuild();
  165. ///
  166. /// let base = dom.base_scope();
  167. ///
  168. /// assert_eq!(base.parent(), None);
  169. /// ```
  170. pub fn parent(&self) -> Option<ScopeId> {
  171. // safety: the pointer to our parent is *always* valid thanks to the bump arena
  172. self.parent.map(|p| unsafe { &*p }.id)
  173. }
  174. /// Get the ID of this Scope within this Dioxus [`crate::VirtualDom`].
  175. ///
  176. /// This ID is not unique across Dioxus [`crate::VirtualDom`]s or across time. IDs will be reused when components are unmounted.
  177. ///
  178. /// # Example
  179. ///
  180. /// ```rust, ignore
  181. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  182. /// dom.rebuild();
  183. /// let base = dom.base_scope();
  184. ///
  185. /// assert_eq!(base.scope_id(), 0);
  186. /// ```
  187. pub fn scope_id(&self) -> ScopeId {
  188. self.id
  189. }
  190. /// Create a subscription that schedules a future render for the reference component
  191. ///
  192. /// ## Notice: you should prefer using [`Self::schedule_update_any`] and [`Self::scope_id`]
  193. pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
  194. let (chan, id) = (self.tasks.sender.clone(), self.scope_id());
  195. Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
  196. }
  197. /// Schedule an update for any component given its [`ScopeId`].
  198. ///
  199. /// A component's [`ScopeId`] can be obtained from `use_hook` or the [`ScopeState::scope_id`] method.
  200. ///
  201. /// This method should be used when you want to schedule an update for a component
  202. pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
  203. let chan = self.tasks.sender.clone();
  204. Arc::new(move |id| {
  205. chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
  206. })
  207. }
  208. /// Mark this scope as dirty, and schedule a render for it.
  209. pub fn needs_update(&self) {
  210. self.needs_update_any(self.scope_id());
  211. }
  212. /// Get the [`ScopeId`] of a mounted component.
  213. ///
  214. /// `ScopeId` is not unique for the lifetime of the [`crate::VirtualDom`] - a [`ScopeId`] will be reused if a component is unmounted.
  215. pub fn needs_update_any(&self, id: ScopeId) {
  216. self.tasks
  217. .sender
  218. .unbounded_send(SchedulerMsg::Immediate(id))
  219. .expect("Scheduler to exist if scope exists");
  220. }
  221. /// Return any context of type T if it exists on this scope
  222. pub fn has_context<T: 'static + Clone>(&self) -> Option<T> {
  223. self.shared_contexts
  224. .borrow()
  225. .iter()
  226. .find(|(k, _)| *k == TypeId::of::<T>())
  227. .map(|(_, v)| v)?
  228. .downcast_ref::<T>()
  229. .cloned()
  230. }
  231. /// Try to retrieve a shared state with type `T` from any parent scope.
  232. ///
  233. /// Clones the state if it exists.
  234. pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
  235. if let Some(this_ctx) = self.has_context() {
  236. return Some(this_ctx);
  237. }
  238. let mut search_parent = self.parent;
  239. while let Some(parent_ptr) = search_parent {
  240. // safety: all parent pointers are valid thanks to the bump arena
  241. let parent = unsafe { &*parent_ptr };
  242. if let Some(shared) = parent
  243. .shared_contexts
  244. .borrow()
  245. .iter()
  246. .find(|(k, _)| *k == TypeId::of::<T>())
  247. {
  248. return shared.1.downcast_ref::<T>().cloned();
  249. }
  250. search_parent = parent.parent;
  251. }
  252. None
  253. }
  254. /// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
  255. ///
  256. /// This is a "fundamental" operation and should only be called during initialization of a hook.
  257. ///
  258. /// For a hook that provides the same functionality, use `use_provide_context` and `use_context` instead.
  259. ///
  260. /// # Example
  261. ///
  262. /// ```rust, ignore
  263. /// struct SharedState(&'static str);
  264. ///
  265. /// static App: Component = |cx| {
  266. /// cx.use_hook(|| cx.provide_context(SharedState("world")));
  267. /// render!(Child {})
  268. /// }
  269. ///
  270. /// static Child: Component = |cx| {
  271. /// let state = cx.consume_state::<SharedState>();
  272. /// render!(div { "hello {state.0}" })
  273. /// }
  274. /// ```
  275. pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
  276. let mut contexts = self.shared_contexts.borrow_mut();
  277. // If the context exists, swap it out for the new value
  278. for ctx in contexts.iter_mut() {
  279. // Swap the ptr directly
  280. if let Some(ctx) = ctx.1.downcast_mut::<T>() {
  281. std::mem::swap(ctx, &mut value.clone());
  282. return value;
  283. }
  284. }
  285. // Else, just push it
  286. contexts.push((TypeId::of::<T>(), Box::new(value.clone())));
  287. value
  288. }
  289. /// Provide a context to the root and then consume it
  290. ///
  291. /// This is intended for "global" state management solutions that would rather be implicit for the entire app.
  292. /// Things like signal runtimes and routers are examples of "singletons" that would benefit from lazy initialization.
  293. ///
  294. /// Note that you should be checking if the context existed before trying to provide a new one. Providing a context
  295. /// when a context already exists will swap the context out for the new one, which may not be what you want.
  296. pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
  297. let mut parent = self;
  298. // Walk upwards until there is no more parent - and tada we have the root
  299. while let Some(next_parent) = parent.parent {
  300. parent = unsafe { &*next_parent };
  301. debug_assert_eq!(parent.scope_id(), ScopeId(0));
  302. }
  303. parent.provide_context(context)
  304. }
  305. /// Pushes the future onto the poll queue to be polled after the component renders.
  306. pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
  307. let id = self.tasks.spawn(self.id, fut);
  308. self.spawned_tasks.borrow_mut().insert(id);
  309. id
  310. }
  311. /// Spawns the future but does not return the [`TaskId`]
  312. pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
  313. self.push_future(fut);
  314. }
  315. /// Spawn a future that Dioxus won't clean up when this component is unmounted
  316. ///
  317. /// This is good for tasks that need to be run after the component has been dropped.
  318. pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
  319. // The root scope will never be unmounted so we can just add the task at the top of the app
  320. let id = self.tasks.spawn(ScopeId(0), fut);
  321. // wake up the scheduler if it is sleeping
  322. self.tasks
  323. .sender
  324. .unbounded_send(SchedulerMsg::TaskNotified(id))
  325. .expect("Scheduler should exist");
  326. self.spawned_tasks.borrow_mut().insert(id);
  327. id
  328. }
  329. /// Informs the scheduler that this task is no longer needed and should be removed.
  330. ///
  331. /// This drops the task immediately.
  332. pub fn remove_future(&self, id: TaskId) {
  333. self.tasks.remove(id);
  334. }
  335. /// Take a lazy [`crate::VNode`] structure and actually build it with the context of the efficient [`bumpalo::Bump`] allocator.
  336. ///
  337. /// ## Example
  338. ///
  339. /// ```ignore
  340. /// fn Component(cx: Scope<Props>) -> Element {
  341. /// // Lazy assemble the VNode tree
  342. /// let lazy_nodes = rsx!("hello world");
  343. ///
  344. /// // Actually build the tree and allocate it
  345. /// cx.render(lazy_tree)
  346. /// }
  347. ///```
  348. pub fn render(&'src self, rsx: LazyNodes<'src, '_>) -> Element<'src> {
  349. let element = rsx.call(self);
  350. let mut listeners = self.attributes_to_drop.borrow_mut();
  351. for attr in element.dynamic_attrs {
  352. match attr.value {
  353. AttributeValue::Any(_) | AttributeValue::Listener(_) => {
  354. let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
  355. listeners.push(unbounded);
  356. }
  357. _ => (),
  358. }
  359. }
  360. let mut props = self.borrowed_props.borrow_mut();
  361. for node in element.dynamic_nodes {
  362. if let DynamicNode::Component(comp) = node {
  363. if !comp.static_props {
  364. let unbounded = unsafe { std::mem::transmute(comp as *const VComponent) };
  365. props.push(unbounded);
  366. }
  367. }
  368. }
  369. Some(element)
  370. }
  371. /// Create a dynamic text node using [`Arguments`] and the [`ScopeState`]'s internal [`Bump`] allocator
  372. pub fn text_node(&'src self, args: Arguments) -> DynamicNode<'src> {
  373. DynamicNode::Text(VText {
  374. value: self.raw_text(args),
  375. id: Default::default(),
  376. })
  377. }
  378. /// Allocate some text inside the [`ScopeState`] from [`Arguments`]
  379. ///
  380. /// Uses the currently active [`Bump`] allocator
  381. pub fn raw_text(&'src self, args: Arguments) -> &'src str {
  382. args.as_str().unwrap_or_else(|| {
  383. use bumpalo::core_alloc::fmt::Write;
  384. let mut str_buf = bumpalo::collections::String::new_in(self.bump());
  385. str_buf.write_fmt(args).unwrap();
  386. str_buf.into_bump_str()
  387. })
  388. }
  389. /// Convert any item that implements [`IntoDynNode`] into a [`DynamicNode`] using the internal [`Bump`] allocator
  390. pub fn make_node<'c, I>(&'src self, into: impl IntoDynNode<'src, I> + 'c) -> DynamicNode {
  391. into.into_vnode(self)
  392. }
  393. /// Create a new [`Attribute`] from a name, value, namespace, and volatile bool
  394. ///
  395. /// "Volatile" referes to whether or not Dioxus should always override the value. This helps prevent the UI in
  396. /// some renderers stay in sync with the VirtualDom's understanding of the world
  397. pub fn attr(
  398. &'src self,
  399. name: &'static str,
  400. value: impl IntoAttributeValue<'src>,
  401. namespace: Option<&'static str>,
  402. volatile: bool,
  403. ) -> Attribute<'src> {
  404. Attribute {
  405. name,
  406. namespace,
  407. volatile,
  408. mounted_element: Default::default(),
  409. value: value.into_value(self.bump()),
  410. }
  411. }
  412. /// Create a new [`DynamicNode::Component`] variant
  413. ///
  414. ///
  415. /// The given component can be any of four signatures. Remember that an [`Element`] is really a [`Result<VNode>`].
  416. ///
  417. /// ```rust, ignore
  418. /// // Without explicit props
  419. /// fn(Scope) -> Element;
  420. /// async fn(Scope<'_>) -> Element;
  421. ///
  422. /// // With explicit props
  423. /// fn(Scope<Props>) -> Element;
  424. /// async fn(Scope<Props<'_>>) -> Element;
  425. /// ```
  426. pub fn component<'child, P>(
  427. &'src self,
  428. component: fn(Scope<'child, P>) -> Element<'child>,
  429. props: P,
  430. fn_name: &'static str,
  431. ) -> DynamicNode<'src>
  432. where
  433. P: Properties + 'child,
  434. 'src: 'child,
  435. {
  436. let vcomp = VProps::new(component, P::memoize, props);
  437. // cast off the lifetime of the render return
  438. let as_dyn: Box<dyn AnyProps<'child> + '_> = Box::new(vcomp);
  439. let extended: Box<dyn AnyProps<'src> + 'src> = unsafe { std::mem::transmute(as_dyn) };
  440. DynamicNode::Component(VComponent {
  441. name: fn_name,
  442. render_fn: component as *const (),
  443. static_props: P::IS_STATIC,
  444. props: RefCell::new(Some(extended)),
  445. scope: Cell::new(None),
  446. })
  447. }
  448. /// Create a new [`EventHandler`] from an [`FnMut`]
  449. pub fn event_handler<T>(&'src self, f: impl FnMut(T) + 'src) -> EventHandler<'src, T> {
  450. let handler: &mut dyn FnMut(T) = self.bump().alloc(f);
  451. let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
  452. let callback = RefCell::new(Some(caller));
  453. EventHandler { callback }
  454. }
  455. /// Create a new [`AttributeValue`] with the listener variant from a callback
  456. ///
  457. /// The callback must be confined to the lifetime of the ScopeState
  458. pub fn listener<T: 'static>(
  459. &'src self,
  460. mut callback: impl FnMut(Event<T>) + 'src,
  461. ) -> AttributeValue<'src> {
  462. // safety: there's no other way to create a dynamicly-dispatched bump box other than alloc + from-raw
  463. // This is the suggested way to build a bumpbox
  464. //
  465. // In theory, we could just use regular boxes
  466. let boxed: BumpBox<'src, dyn FnMut(_) + 'src> = unsafe {
  467. BumpBox::from_raw(self.bump().alloc(move |event: Event<dyn Any>| {
  468. if let Ok(data) = event.data.downcast::<T>() {
  469. callback(Event {
  470. propagates: event.propagates,
  471. data,
  472. });
  473. }
  474. }))
  475. };
  476. AttributeValue::Listener(RefCell::new(Some(boxed)))
  477. }
  478. /// Create a new [`AttributeValue`] with a value that implements [`AnyValue`]
  479. pub fn any_value<T: AnyValue>(&'src self, value: T) -> AttributeValue<'src> {
  480. // safety: there's no other way to create a dynamicly-dispatched bump box other than alloc + from-raw
  481. // This is the suggested way to build a bumpbox
  482. //
  483. // In theory, we could just use regular boxes
  484. let boxed: BumpBox<'src, dyn AnyValue> =
  485. unsafe { BumpBox::from_raw(self.bump().alloc(value)) };
  486. AttributeValue::Any(RefCell::new(Some(boxed)))
  487. }
  488. /// Inject an error into the nearest error boundary and quit rendering
  489. ///
  490. /// The error doesn't need to implement Error or any specific traits since the boundary
  491. /// itself will downcast the error into a trait object.
  492. pub fn throw(&self, error: impl Debug + 'static) -> Option<()> {
  493. if let Some(cx) = self.consume_context::<Rc<ErrorBoundary>>() {
  494. cx.insert_error(self.scope_id(), Box::new(error));
  495. }
  496. // Always return none during a throw
  497. None
  498. }
  499. /// Mark this component as suspended and then return None
  500. pub fn suspend(&self) -> Option<Element> {
  501. self.suspended.set(true);
  502. None
  503. }
  504. /// Store a value between renders. The foundational hook for all other hooks.
  505. ///
  506. /// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render). The return value of this closure is stored for the lifetime of the component, and a mutable reference to it is provided on every render as the return value of `use_hook`.
  507. ///
  508. /// When the component is unmounted (removed from the UI), the value is dropped. This means you can return a custom type and provide cleanup code by implementing the [`Drop`] trait
  509. ///
  510. /// # Example
  511. ///
  512. /// ```
  513. /// use dioxus_core::ScopeState;
  514. ///
  515. /// // prints a greeting on the initial render
  516. /// pub fn use_hello_world(cx: &ScopeState) {
  517. /// cx.use_hook(|| println!("Hello, world!"));
  518. /// }
  519. /// ```
  520. #[allow(clippy::mut_from_ref)]
  521. pub fn use_hook<State: 'static>(&self, initializer: impl FnOnce() -> State) -> &mut State {
  522. let cur_hook = self.hook_idx.get();
  523. let mut hooks = self.hooks.try_borrow_mut().expect("The hook list is already borrowed: This error is likely caused by trying to use a hook inside a hook which violates the rules of hooks.");
  524. if cur_hook >= hooks.len() {
  525. hooks.push(Box::new(UnsafeCell::new(initializer())));
  526. }
  527. hooks
  528. .get(cur_hook)
  529. .and_then(|inn| {
  530. self.hook_idx.set(cur_hook + 1);
  531. let raw_ref = unsafe { &mut *inn.get() };
  532. raw_ref.downcast_mut::<State>()
  533. })
  534. .expect(
  535. r#"
  536. Unable to retrieve the hook that was initialized at this index.
  537. Consult the `rules of hooks` to understand how to use hooks properly.
  538. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  539. Functions prefixed with "use" should never be called conditionally.
  540. "#,
  541. )
  542. }
  543. }