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