# Context

Source: https://signy.dev/documentation/1/components/context/

Share a value with every component below.

## Create a context

`createContext(defaultValue, name)` returns a context. A component provides a value, and any component below it injects it. The default value is used when no component provides one.

```js
const ThemeContext = createContext<Signal<'light' | 'dark'>>(undefined, 'Theme');
```

## Provide and inject

Provide in `setup()`. Provide a signal when the value changes.

```js
const { Component, Signal, application, html, createContext } = Signy;

const ThemeContext = createContext(undefined, "Theme");

class ThemeLabel extends Component {
  render() {
    const theme = ThemeContext.inject(this);
    return html`<p>The theme is ${() => theme.value}</p>`;
  }
}

class App extends Component {
  theme = new Signal("light");

  setup() {
    ThemeContext.provide(this, this.theme);
  }

  render() {
    return html`
      <button onClick=${() => this.theme.set((t) => (t === "light" ? "dark" : "light"))}>
        Switch theme
      </button>
      <${ThemeLabel} />
    `;
  }
}

application(App).mount("#context-theme");
```

## Required context

`createRequiredContext(name)` has no default. Injecting it with no provider above throws, which catches a missing provider early.
