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