dioxus_core/
global_context.rs

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