yewstack/yew · error

no ctx found

Error message

no ctx found

What it means

This snippet from the Yew docs (HOC example) calls use_context::<Theme>(), which returns Option<Rc<Theme>> - None when no ContextProvider<Theme> ancestor is mounted - and the expect turns that into a panic. It fires whenever a context consumer renders without a matching provider of the same type above it in the component tree.

Source

Thrown at website/versioned_docs/version-0.21/advanced-topics/struct-components/hoc.mdx:43

#[function_component]
pub fn App() -> Html {
    let ctx = use_state(|| Theme {
        foreground: "#000000".to_owned(),
        background: "#eeeeee".to_owned(),
    });

    html! {
        <ContextProvider<Theme> context={(*ctx).clone()}>
            <ThemedButtonHOC />
        </ContextProvider<Theme>>
    }
}

// highlight-start
#[function_component]
pub fn ThemedButtonHOC() -> Html {
    let theme = use_context::<Theme>().expect("no ctx found");

    html! {<ThemedButtonStructComponent {theme} />}
}
// highlight-end

#[derive(Properties, PartialEq)]
pub struct Props {
    pub theme: Theme,
}

struct ThemedButtonStructComponent;

impl Component for ThemedButtonStructComponent {
    type Message = ();
    type Properties = Props;

    fn create(_ctx: &Context<Self>) -> Self {
        Self

View on GitHub (pinned to 0e4a05472f)

Solutions

  1. Wrap the tree above every consumer: <ContextProvider<Theme> context={theme}> ... </ContextProvider<Theme>>
  2. Verify the provider is an ancestor (not a sibling) of the consumer
  3. If the context is genuinely optional, handle None instead of expecting: use_context::<Theme>().unwrap_or_default()
  4. In tests, mount consumers under a provider or assert against the default

Example fix

// before
#[function_component]
pub fn App() -> Html {
    html! { <ThemedButtonHOC /> } // no provider above -> panic
}

// after
#[function_component]
pub fn App() -> Html {
    let theme = use_state(|| Theme::default());
    html! {
        <ContextProvider<Theme> context={(*theme).clone()}>
            <ThemedButtonHOC />
        </ContextProvider<Theme>>
    }
}
Defensive patterns

Strategy: fallback

Prevention

When it happens

Trigger: Rendering ThemedButtonHOC (or any use_context::<Theme>() consumer) outside <ContextProvider<Theme> ...>; a provider supplying a different type; a provider positioned below or beside the consumer instead of above it.

Common situations: Forgetting the provider at the app root; refactoring the tree so consumers slip outside the provider; rendering the component in isolation in tests or stories; subtle type mismatches between what is provided and what is requested.

Related errors


AI-assisted analysis of yewstack/yew@0e4a05472f (2026-08-22). Data as JSON: /api/errors/96aeef12fddc9dbd. Report an issue: GitHub.