1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use ;
/// Try to consume some context in the tree, returning `None` if it is not found.
///
/// This is a **hook** — the context value is captured once on the first render and cached
/// for the lifetime of the component. It follows the [rules of hooks](https://dioxuslabs.com/learn/essentials/state/#rules-of-hooks),
/// meaning it must be called unconditionally at the top level of a component.
///
/// If you need to read context from outside a component body (e.g., inside an event handler,
/// async task, or spawned future), use [`try_consume_context`] instead,
/// which can be called anywhere the Dioxus runtime is active.
/// Consume some context in the tree, panicking if it is not found.
///
/// This is a **hook** — the context value is captured once on the first render and cached
/// for the lifetime of the component. It follows the [rules of hooks](https://dioxuslabs.com/learn/essentials/state/#rules-of-hooks),
/// meaning it must be called unconditionally at the top level of a component.
///
/// If you need to read context from outside a component body (e.g., inside an event handler,
/// async task, or spawned future), use [`consume_context`] instead,
/// which can be called anywhere the Dioxus runtime is active.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[derive(Clone, Copy, PartialEq, Debug)]
/// # enum Theme { Dark, Light }
/// fn Parent() -> Element {
/// use_context_provider(|| Theme::Dark);
/// rsx! { Child {} }
/// }
/// #[component]
/// fn Child() -> Element {
/// //gets context provided by parent element with use_context_provider
/// let user_theme = use_context::<Theme>();
/// rsx! { "user using dark mode: {user_theme == Theme::Dark}" }
/// }
/// ```
/// Provide some context via the tree and return a reference to it
///
/// Once the context has been provided, it is immutable. Mutations should be done via interior mutability.
/// Context can be read by any child components of the context provider, and is a solution to prop
/// drilling, using a context provider with a Signal inside is a good way to provide global/shared
/// state in your app:
/// ```rust
/// # use dioxus::prelude::*;
///fn app() -> Element {
/// use_context_provider(|| Signal::new(0));
/// rsx! { Child {} }
///}
/// // This component does read from the signal, so when the signal changes it will rerun
///#[component]
///fn Child() -> Element {
/// let mut signal: Signal<i32> = use_context();
/// rsx! {
/// button { onclick: move |_| signal += 1, "increment context" }
/// p {"{signal}"}
/// }
///}
/// ```