use_root_context.rs 1.1 KB

1234567891011121314151617181920212223242526
  1. use dioxus_core::{prelude::provide_root_context, prelude::try_consume_context, use_hook};
  2. /// 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.
  3. ///
  4. /// 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.
  5. ///
  6. /// # Example
  7. /// ```rust
  8. /// # #[derive(Clone)]
  9. /// # struct Logger;
  10. /// use dioxus::prelude::*;
  11. ///
  12. /// fn use_logger() -> Logger {
  13. /// // 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.
  14. /// use_root_context(|| Logger)
  15. /// }
  16. /// ```
  17. #[doc = include_str!("../docs/rules_of_hooks.md")]
  18. #[doc = include_str!("../docs/moving_state_around.md")]
  19. pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -> T {
  20. use_hook(|| {
  21. try_consume_context::<T>()
  22. // If no context is provided, create a new one at the root
  23. .unwrap_or_else(|| provide_root_context(new()))
  24. })
  25. }