dioxus_hooks/
use_root_context.rs

1use dioxus_core::{prelude::provide_root_context, prelude::try_consume_context, use_hook};
2
3/// Try to get a value from the root of the virtual dom, if it doesn't exist, create a new one with the closure provided.
4///
5/// This is useful for global context inside of libraries. Instead of having the user provide context in the root of their app, you can use this hook to create a context at the root automatically.
6///
7/// # Example
8/// ```rust
9/// # #[derive(Clone)]
10/// # struct Logger;
11/// use dioxus::prelude::*;
12///
13/// fn use_logger() -> Logger {
14///     // We want one logger per app in the root. Instead of forcing the user to always provide a logger, we can insert a default logger if one doesn't exist.
15///     use_root_context(|| Logger)
16/// }
17/// ```
18#[doc = include_str!("../docs/rules_of_hooks.md")]
19#[doc = include_str!("../docs/moving_state_around.md")]
20pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -> T {
21    use_hook(|| {
22        try_consume_context::<T>()
23            // If no context is provided, create a new one at the root
24            .unwrap_or_else(|| provide_root_context(new()))
25    })
26}