dioxus_core/
global_context.rs

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