--- title: "use_context" --- [Contexts](../contexts.mdx) will be introduced later. `use_context` is used for consuming [contexts](../contexts.mdx) in function components. ## Example ```rust use yew::{ContextProvider, function_component, html, use_context, use_state, Html}; /// App theme #[derive(Clone, Debug, PartialEq)] struct Theme { foreground: String, background: String, } /// Main component #[function_component] pub fn App() -> Html { let ctx = use_state(|| Theme { foreground: "#000000".to_owned(), background: "#eeeeee".to_owned(), }); html! { // `ctx` is type `Rc>` while we need `Theme` // so we deref it. // It derefs to `&Theme`, hence the clone context={(*ctx).clone()}> // Every child here and their children will have access to this context. > } } /// The toolbar. /// This component has access to the context #[function_component] pub fn Toolbar() -> Html { html! {
} } /// Button placed in `Toolbar`. /// As this component is a child of `ThemeContextProvider` in the component tree, it also has access to the context. #[function_component] pub fn ThemedButton() -> Html { //highlight-next-line let theme = use_context::().expect("no ctx found"); html! { } } ```