yewstack/yew · error

no ctx found

Error message

no ctx found

What it means

The contexts tutorial calls use_context::<Theme>() inside ThemedButton and expects a value; the Option is None unless a ContextProvider<Theme> is mounted above the button (in the docs, ThemeContextProvider supplies it). Rendered standalone - or after a refactor removes the provider - the expect panics.

Source

Thrown at website/versioned_docs/version-0.21/concepts/contexts.mdx:144

}

/// The toolbar.
/// This component has access to the context
#[function_component]
pub fn Toolbar() -> Html {
    html! {
        <div>
            <ThemedButton />
        </div>
    }
}

/// 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 {
    let theme = use_context::<Theme>().expect("no ctx found");

    html! {
        <button style={format!("background: {}; color: {};", theme.background, theme.foreground)}>
            { "Click me!" }
        </button>
    }
}
```

### Step 2: Consuming context

#### Function components

`use_context` hook is used to consume contexts in function components.
See [docs for use_context](https://yew-rs-api.web.app/next/yew/functional/fn.use_context.html) to learn more.

#### Struct components

View on GitHub (pinned to 0e4a05472f)

Solutions

  1. Wrap consumers with the provider as the tutorial does: <ContextProvider<Theme> context={...}> ... </ContextProvider<Theme>>
  2. Confirm the consumer is a descendant of the provider, not a sibling
  3. Treat context as optional where appropriate: use_context::<Theme>().unwrap_or_default()
  4. In isolated tests, provide the context explicitly or assert against the default

Example fix

// before
html! { <ThemedButton /> } // no ThemeContextProvider above -> panic

// after
html! {
    <ContextProvider<Theme> context={Theme::default()}>
        <ThemedButton />
    </ContextProvider<Theme>>
}
Defensive patterns

Strategy: fallback

Prevention

When it happens

Trigger: Mounting ThemedButton without <ContextProvider<Theme>> above it; provider and consumer requesting different types; the provider itself being conditionally not rendered on some pass.

Common situations: Tests or stories rendering the button in isolation; app-tree refactors that move consumers out from under the provider; learners running snippets piecemeal without the provider component.

Related errors


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