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
- Wrap consumers with the provider as the tutorial does: <ContextProvider<Theme> context={...}> ... </ContextProvider<Theme>>
- Confirm the consumer is a descendant of the provider, not a sibling
- Treat context as optional where appropriate: use_context::<Theme>().unwrap_or_default()
- 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
- Mount <ContextProvider<Theme>> above every ThemedButton before relying on use_context
- Where a default exists, use use_context::<Theme>().unwrap_or_default() rather than expect
- Wrap isolated component tests with a provider or use the default theme
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
- no ctx found
- I'm sure this event has a target!
- mouse event doesn't have a target
- event target should be of type HtmlElement
- global document not set
AI-assisted analysis of yewstack/yew@0e4a05472f (2026-08-22).
Data as JSON: /api/errors/b6d3ed516353ceef.
Report an issue: GitHub.