use_context.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use dioxus_core::{
  2. prelude::{consume_context, provide_context, try_consume_context},
  3. use_hook,
  4. };
  5. /// Consume some context in the tree, providing a sharable handle to the value
  6. ///
  7. /// Does not regenerate the value if the value is changed at the parent.
  8. #[must_use]
  9. pub fn try_use_context<T: 'static + Clone>() -> Option<T> {
  10. use_hook(|| try_consume_context::<T>())
  11. }
  12. /// Consume some context in the tree, providing a sharable handle to the value
  13. ///
  14. /// Does not regenerate the value if the value is changed at the parent.
  15. /// ```rust
  16. /// # use dioxus::prelude::*;
  17. /// # #[derive(Clone, Copy, PartialEq, Debug)]
  18. /// # enum Theme { Dark, Light }
  19. /// fn Parent() -> Element {
  20. /// use_context_provider(|| Theme::Dark);
  21. /// rsx! { Child {} }
  22. /// }
  23. /// #[component]
  24. /// fn Child() -> Element {
  25. /// //gets context provided by parent element with use_context_provider
  26. /// let user_theme = use_context::<Theme>();
  27. /// rsx! { "user using dark mode: {user_theme == Theme::Dark}" }
  28. /// }
  29. /// ```
  30. #[must_use]
  31. pub fn use_context<T: 'static + Clone>() -> T {
  32. use_hook(|| consume_context::<T>())
  33. }
  34. /// Provide some context via the tree and return a reference to it
  35. ///
  36. /// Once the context has been provided, it is immutable. Mutations should be done via interior mutability.
  37. /// Context can be read by any child components of the context provider, and is a solution to prop
  38. /// drilling, using a context provider with a Signal inside is a good way to provide global/shared
  39. /// state in your app:
  40. /// ```rust
  41. /// # use dioxus::prelude::*;
  42. ///fn app() -> Element {
  43. /// use_context_provider(|| Signal::new(0));
  44. /// rsx! { Child {} }
  45. ///}
  46. /// // This component does read from the signal, so when the signal changes it will rerun
  47. ///#[component]
  48. ///fn Child() -> Element {
  49. /// let mut signal: Signal<i32> = use_context();
  50. /// rsx! {
  51. /// button { onclick: move |_| signal += 1, "increment context" }
  52. /// p {"{signal}"}
  53. /// }
  54. ///}
  55. /// ```
  56. pub fn use_context_provider<T: 'static + Clone>(f: impl FnOnce() -> T) -> T {
  57. use_hook(|| provide_context(f()))
  58. }