dioxus_core/
global_context.rs

1use crate::prelude::SuspenseContext;
2use crate::runtime::RuntimeError;
3use crate::{innerlude::SuspendedFuture, runtime::Runtime, CapturedError, Element, ScopeId, Task};
4use std::future::Future;
5use std::sync::Arc;
6
7/// Get the current scope id
8pub fn current_scope_id() -> Result<ScopeId, RuntimeError> {
9    Runtime::with(|rt| rt.current_scope_id().ok())
10        .ok()
11        .flatten()
12        .ok_or(RuntimeError::new())
13}
14
15#[doc(hidden)]
16/// Check if the virtual dom is currently inside of the body of a component
17pub fn vdom_is_rendering() -> bool {
18    Runtime::with(|rt| rt.rendering.get()).unwrap_or_default()
19}
20
21/// Throw a [`CapturedError`] into the current scope. The error will bubble up to the nearest [`crate::prelude::ErrorBoundary()`] or the root of the app.
22///
23/// # Examples
24/// ```rust, no_run
25/// # use dioxus::prelude::*;
26/// fn Component() -> Element {
27///     let request = spawn(async move {
28///         match reqwest::get("https://api.example.com").await {
29///             Ok(_) => unimplemented!(),
30///             // You can explicitly throw an error into a scope with throw_error
31///             Err(err) => ScopeId::APP.throw_error(err)
32///         }
33///     });
34///
35///     unimplemented!()
36/// }
37/// ```
38pub fn throw_error(error: impl Into<CapturedError> + 'static) {
39    current_scope_id()
40        .unwrap_or_else(|e| panic!("{}", e))
41        .throw_error(error)
42}
43
44/// Get the suspense context the current scope is in
45pub fn suspense_context() -> Option<SuspenseContext> {
46    current_scope_id()
47        .unwrap_or_else(|e| panic!("{}", e))
48        .suspense_context()
49}
50
51/// Consume context from the current scope
52pub fn try_consume_context<T: 'static + Clone>() -> Option<T> {
53    Runtime::with_current_scope(|cx| cx.consume_context::<T>())
54        .ok()
55        .flatten()
56}
57
58/// Consume context from the current scope
59pub fn consume_context<T: 'static + Clone>() -> T {
60    Runtime::with_current_scope(|cx| cx.consume_context::<T>())
61        .ok()
62        .flatten()
63        .unwrap_or_else(|| panic!("Could not find context {}", std::any::type_name::<T>()))
64}
65
66/// Consume context from the current scope
67pub fn consume_context_from_scope<T: 'static + Clone>(scope_id: ScopeId) -> Option<T> {
68    Runtime::with(|rt| {
69        rt.get_state(scope_id)
70            .and_then(|cx| cx.consume_context::<T>())
71    })
72    .ok()
73    .flatten()
74}
75
76/// Check if the current scope has a context
77pub fn has_context<T: 'static + Clone>() -> Option<T> {
78    Runtime::with_current_scope(|cx| cx.has_context::<T>())
79        .ok()
80        .flatten()
81}
82
83/// Provide context to the current scope
84pub fn provide_context<T: 'static + Clone>(value: T) -> T {
85    Runtime::with_current_scope(|cx| cx.provide_context(value)).unwrap()
86}
87
88/// Provide a context to the root scope
89pub fn provide_root_context<T: 'static + Clone>(value: T) -> T {
90    Runtime::with_current_scope(|cx| cx.provide_root_context(value)).unwrap()
91}
92
93/// Suspended the current component on a specific task and then return None
94pub fn suspend(task: Task) -> Element {
95    Err(crate::innerlude::RenderError::Suspended(
96        SuspendedFuture::new(task),
97    ))
98}
99
100/// Start a new future on the same thread as the rest of the VirtualDom.
101///
102/// **You should generally use `spawn` instead of this method unless you specifically need to run a task during suspense**
103///
104/// This future will not contribute to suspense resolving but it will run during suspense.
105///
106/// Because this future runs during suspense, you need to be careful to work with hydration. It is not recommended to do any async IO work in this future, as it can easily cause hydration issues. However, you can use isomorphic tasks to do work that can be consistently replicated on the server and client like logging or responding to state changes.
107///
108/// ```rust, no_run
109/// # use dioxus::prelude::*;
110/// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues.
111/// let mut state = use_signal(|| None);
112/// spawn_isomorphic(async move {
113///     state.set(Some(reqwest::get("https://api.example.com").await));
114/// });
115///
116/// // ✅ You may wait for a signal to change and then log it
117/// let mut state = use_signal(|| 0);
118/// spawn_isomorphic(async move {
119///     loop {
120///         tokio::time::sleep(std::time::Duration::from_secs(1)).await;
121///         println!("State is {state}");
122///     }
123/// });
124/// ```
125///
126#[doc = include_str!("../docs/common_spawn_errors.md")]
127pub fn spawn_isomorphic(fut: impl Future<Output = ()> + 'static) -> Task {
128    Runtime::with_current_scope(|cx| cx.spawn_isomorphic(fut)).unwrap()
129}
130
131/// Spawns the future and returns the [`Task`]. This task will automatically be canceled when the component is dropped.
132///
133/// # Example
134/// ```rust
135/// use dioxus::prelude::*;
136///
137/// fn App() -> Element {
138///     rsx! {
139///         button {
140///             onclick: move |_| {
141///                 spawn(async move {
142///                     tokio::time::sleep(std::time::Duration::from_secs(1)).await;
143///                     println!("Hello World");
144///                 });
145///             },
146///             "Print hello in one second"
147///         }
148///     }
149/// }
150/// ```
151///
152#[doc = include_str!("../docs/common_spawn_errors.md")]
153pub fn spawn(fut: impl Future<Output = ()> + 'static) -> Task {
154    Runtime::with_current_scope(|cx| cx.spawn(fut)).unwrap()
155}
156
157/// Queue an effect to run after the next render. You generally shouldn't need to interact with this function directly. [use_effect](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) will call this function for you.
158pub fn queue_effect(f: impl FnOnce() + 'static) {
159    Runtime::with_current_scope(|cx| cx.queue_effect(f)).unwrap()
160}
161
162/// Spawn a future that Dioxus won't clean up when this component is unmounted
163///
164/// This is good for tasks that need to be run after the component has been dropped.
165///
166/// **This will run the task in the root scope. Any calls to global methods inside the future (including `context`) will be run in the root scope.**
167///
168/// # Example
169///
170/// ```rust
171/// use dioxus::prelude::*;
172///
173/// // The parent component can create and destroy children dynamically
174/// fn App() -> Element {
175///     let mut count = use_signal(|| 0);
176///
177///     rsx! {
178///         button {
179///             onclick: move |_| count += 1,
180///             "Increment"
181///         }
182///         button {
183///             onclick: move |_| count -= 1,
184///             "Decrement"
185///         }
186///
187///         for id in 0..10 {
188///             Child { id }
189///         }
190///     }
191/// }
192///
193/// #[component]
194/// fn Child(id: i32) -> Element {
195///     rsx! {
196///         button {
197///             onclick: move |_| {
198///                 // This will spawn a task in the root scope that will run forever
199///                 // It will keep running even if you drop the child component by decreasing the count
200///                 spawn_forever(async move {
201///                     loop {
202///                         tokio::time::sleep(std::time::Duration::from_secs(1)).await;
203///                         println!("Running task spawned in child component {id}");
204///                     }
205///                 });
206///             },
207///             "Spawn background task"
208///         }
209///     }
210/// }
211/// ```
212///
213#[doc = include_str!("../docs/common_spawn_errors.md")]
214pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Option<Task> {
215    Runtime::with_scope(ScopeId::ROOT, |cx| cx.spawn(fut)).ok()
216}
217
218/// Informs the scheduler that this task is no longer needed and should be removed.
219///
220/// This drops the task immediately.
221pub fn remove_future(id: Task) {
222    Runtime::with(|rt| rt.remove_task(id)).expect("Runtime to exist");
223}
224
225/// Store a value between renders. The foundational hook for all other hooks.
226///
227/// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render).
228/// `use_hook` will return a clone of the value on every render.
229///
230/// In order to clean up resources you would need to implement the [`Drop`] trait for an inner value stored in a RC or similar (Signals for instance),
231/// as these only drop their inner value once all references have been dropped, which only happens when the component is dropped.
232///
233/// <div class="warning">
234///
235/// `use_hook` is not reactive. It just returns the value on every render. If you need state that will track changes, use [`use_signal`](dioxus::prelude::use_signal) instead.
236///
237/// ❌ Don't use `use_hook` with `Rc<RefCell<T>>` for state. It will not update the UI and other hooks when the state changes.
238/// ```rust
239/// use dioxus::prelude::*;
240/// use std::rc::Rc;
241/// use std::cell::RefCell;
242///
243/// pub fn Comp() -> Element {
244///     let count = use_hook(|| Rc::new(RefCell::new(0)));
245///
246///     rsx! {
247///         button {
248///             onclick: move |_| *count.borrow_mut() += 1,
249///             "{count.borrow()}"
250///         }
251///     }
252/// }
253/// ```
254///
255/// ✅ Use `use_signal` instead.
256/// ```rust
257/// use dioxus::prelude::*;
258///
259/// pub fn Comp() -> Element {
260///     let mut count = use_signal(|| 0);
261///
262///     rsx! {
263///         button {
264///             onclick: move |_| count += 1,
265///             "{count}"
266///         }
267///     }
268/// }
269/// ```
270///
271/// </div>
272///
273/// # Example
274///
275/// ```rust, no_run
276/// use dioxus::prelude::*;
277///
278/// // prints a greeting on the initial render
279/// pub fn use_hello_world() {
280///     use_hook(|| println!("Hello, world!"));
281/// }
282/// ```
283///
284/// # Custom Hook Example
285///
286/// ```rust, no_run
287/// use dioxus::prelude::*;
288///
289/// pub struct InnerCustomState(usize);
290///
291/// impl Drop for InnerCustomState {
292///     fn drop(&mut self){
293///         println!("Component has been dropped.");
294///     }
295/// }
296///
297/// #[derive(Clone, Copy)]
298/// pub struct CustomState {
299///     inner: Signal<InnerCustomState>
300/// }
301///
302/// pub fn use_custom_state() -> CustomState {
303///     use_hook(|| CustomState {
304///         inner: Signal::new(InnerCustomState(0))
305///     })
306/// }
307/// ```
308#[track_caller]
309pub fn use_hook<State: Clone + 'static>(initializer: impl FnOnce() -> State) -> State {
310    Runtime::with_current_scope(|cx| cx.use_hook(initializer)).unwrap()
311}
312
313/// Get the current render since the inception of this component
314///
315/// This can be used as a helpful diagnostic when debugging hooks/renders, etc
316pub fn generation() -> usize {
317    Runtime::with_current_scope(|cx| cx.generation()).unwrap()
318}
319
320/// Get the parent of the current scope if it exists
321pub fn parent_scope() -> Option<ScopeId> {
322    Runtime::with_current_scope(|cx| cx.parent_id())
323        .ok()
324        .flatten()
325}
326
327/// Mark the current scope as dirty, causing it to re-render
328pub fn needs_update() {
329    let _ = Runtime::with_current_scope(|cx| cx.needs_update());
330}
331
332/// Mark the current scope as dirty, causing it to re-render
333pub fn needs_update_any(id: ScopeId) {
334    let _ = Runtime::with_current_scope(|cx| cx.needs_update_any(id));
335}
336
337/// Schedule an update for the current component
338///
339/// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime.
340///
341/// You should prefer [`schedule_update_any`] if you need to update multiple components.
342#[track_caller]
343pub fn schedule_update() -> Arc<dyn Fn() + Send + Sync> {
344    Runtime::with_current_scope(|cx| cx.schedule_update()).unwrap_or_else(|e| panic!("{}", e))
345}
346
347/// Schedule an update for any component given its [`ScopeId`].
348///
349/// A component's [`ScopeId`] can be obtained from the [`current_scope_id`] method.
350///
351/// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime.
352#[track_caller]
353pub fn schedule_update_any() -> Arc<dyn Fn(ScopeId) + Send + Sync> {
354    Runtime::with_current_scope(|cx| cx.schedule_update_any()).unwrap_or_else(|e| panic!("{}", e))
355}
356
357/// Creates a callback that will be run before the component is removed.
358/// This can be used to clean up side effects from the component
359/// (created with [`use_effect`](dioxus::prelude::use_effect)).
360///
361/// Note:
362/// Effects do not run on the server, but use_drop **DOES**. It runs any time the component is dropped including during SSR rendering on the server. If your clean up logic targets web, the logic has to be gated by a feature, see the below example for details.
363///
364/// Example:
365/// ```rust
366/// use dioxus::prelude::*;
367///
368/// fn app() -> Element {
369///     let mut state = use_signal(|| true);
370///     rsx! {
371///         for _ in 0..100 {
372///             h1 {
373///                 "spacer"
374///             }
375///         }
376///         if state() {
377///             child_component {}
378///         }
379///         button {
380///             onclick: move |_| {
381///                 state.toggle()
382///             },
383///             "Unmount element"
384///         }
385///     }
386/// }
387///
388/// fn child_component() -> Element {
389///     let mut original_scroll_position = use_signal(|| 0.0);
390///
391///     use_effect(move || {
392///         let window = web_sys::window().unwrap();
393///         let document = window.document().unwrap();
394///         let element = document.get_element_by_id("my_element").unwrap();
395///         element.scroll_into_view();
396///         original_scroll_position.set(window.scroll_y().unwrap());
397///     });
398///
399///     use_drop(move || {
400///         // This only make sense to web and hence the `web!` macro
401///         web! {
402///             /// restore scroll to the top of the page
403///             let window = web_sys::window().unwrap();
404///             window.scroll_with_x_and_y(original_scroll_position(), 0.0);
405///         }
406///     });
407///
408///     rsx! {
409///         div {
410///             id: "my_element",
411///             "hello"
412///         }
413///     }
414/// }
415/// ```
416#[doc(alias = "use_on_unmount")]
417pub fn use_drop<D: FnOnce() + 'static>(destroy: D) {
418    struct LifeCycle<D: FnOnce()> {
419        /// Wrap the closure in an option so that we can take it out on drop.
420        ondestroy: Option<D>,
421    }
422
423    /// On drop, we want to run the closure.
424    impl<D: FnOnce()> Drop for LifeCycle<D> {
425        fn drop(&mut self) {
426            if let Some(f) = self.ondestroy.take() {
427                f();
428            }
429        }
430    }
431
432    // We need to impl clone for the lifecycle, but we don't want the drop handler for the closure to be called twice.
433    impl<D: FnOnce()> Clone for LifeCycle<D> {
434        fn clone(&self) -> Self {
435            Self { ondestroy: None }
436        }
437    }
438
439    use_hook(|| LifeCycle {
440        ondestroy: Some(destroy),
441    });
442}
443
444/// A hook that allows you to insert a "before render" function.
445///
446/// This function will always be called before dioxus tries to render your component. This should be used for safely handling
447/// early returns
448pub fn use_before_render(f: impl FnMut() + 'static) {
449    use_hook(|| before_render(f));
450}
451
452/// Push this function to be run after the next render
453///
454/// This function will always be called before dioxus tries to render your component. This should be used for safely handling
455/// early returns
456pub fn use_after_render(f: impl FnMut() + 'static) {
457    use_hook(|| after_render(f));
458}
459
460/// Push a function to be run before the next render
461/// This is a hook and will always run, so you can't unschedule it
462/// Will run for every progression of suspense, though this might change in the future
463pub fn before_render(f: impl FnMut() + 'static) {
464    let _ = Runtime::with_current_scope(|cx| cx.push_before_render(f));
465}
466
467/// Push a function to be run after the render is complete, even if it didn't complete successfully
468pub fn after_render(f: impl FnMut() + 'static) {
469    let _ = Runtime::with_current_scope(|cx| cx.push_after_render(f));
470}
471
472/// Use a hook with a cleanup function
473pub fn use_hook_with_cleanup<T: Clone + 'static>(
474    hook: impl FnOnce() -> T,
475    cleanup: impl FnOnce(T) + 'static,
476) -> T {
477    let value = use_hook(hook);
478    let _value = value.clone();
479    use_drop(move || cleanup(_value));
480    value
481}
482
483/// Force every component to be dirty and require a re-render. Used by hot-reloading.
484///
485/// This might need to change to a different flag in the event hooks order changes within components.
486/// What we really need is a way to mark components as needing a complete rebuild if they were hit by changes.
487pub fn force_all_dirty() {
488    Runtime::with(|rt| {
489        rt.scope_states.borrow_mut().iter().for_each(|state| {
490            if let Some(scope) = state.as_ref() {
491                scope.needs_update();
492            }
493        });
494    })
495    .expect("Runtime to exist");
496}