# Context

> provide and inject share a value with every descendant under a key. Each framework gets its own context, from React's createContext to Angular's InjectionToken.

Some values belong to a whole subtree rather than one component: a theme, a locale, the depth of a nested outline, the state of a set of tabs. Passing them down as props through every level couples components that only pass them on. A component provides such a value under an injection key, and any descendant injects it, however deep.

## Keys

An injection key is an exported top-level `const` of the `.uf.tsx` module whose component provides it, typed `InjectionKey<T>` and set to a `Symbol` with a description:

<!-- prettier-ignore -->
```tsx [ThemeProvider.uf.tsx]
import { provide } from "@uxfront/unframework";
import type { InjectionKey } from "@uxfront/unframework";

import Badge from "./Badge.uf.tsx";

export interface Theme {
  accent: string;
  label: string;
}

export const ThemeKey: InjectionKey<Theme> = Symbol("uf.theme");

export default function ThemeProvider() {
  provide(ThemeKey, { accent: "teal", label: "Teal" });
  return (
    <section aria-label="Themed">
      <Badge text="New" />
    </section>
  );
}
```

<!-- prettier-ignore -->
```tsx [Badge.uf.tsx]
import { inject } from "@uxfront/unframework";

import { ThemeKey } from "./ThemeProvider.uf.tsx";

export default function Badge({ text }: { text: string }) {
  const theme = inject(ThemeKey);
  return (
    <span class={["badge", theme?.accent]}>
      {text} in {theme?.label ?? "no theme"}
    </span>
  );
}
```

`ThemeProvider` provides a theme to everything it renders, and `Badge` imports the key and injects the theme. With no provider above it, `inject` gives `undefined`, so `Badge` reads `theme?.label`. Each framework writes the key in its own form, into the provider's output:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [ThemeProvider.tsx]
import Badge from "./Badge";
import { type ComponentPropsWithRef, createContext, useState } from "react";

export interface Theme {
  accent: string;
  label: string;
}

export type ThemeProviderAttributes = Omit<ComponentPropsWithRef<"section">, "children">;

export const ThemeKey = createContext<Theme | undefined>(undefined);

export default function ThemeProvider({
  className,
  style,
  ...attributes
}: ThemeProviderAttributes) {
  const [themeValue] = useState({ accent: "teal", label: "Teal" });

  return (
    <ThemeKey value={themeValue}>
      <section aria-label="Themed" className={className} style={style} {...attributes}>
        <Badge text="New" />
      </section>
    </ThemeKey>
  );
}
```

<!-- prettier-ignore -->
```tsx [Badge.tsx]
import { ThemeKey } from "./ThemeProvider";
import { cx } from "./_unframework/cx";
import { type ComponentPropsWithRef, use } from "react";

export type BadgeAttributes = Omit<ComponentPropsWithRef<"span">, "text" | "children">;

export default function Badge({
  text,
  className,
  style,
  ...attributes
}: { text: string } & BadgeAttributes) {
  const theme = use(ThemeKey);

  return (
    <span className={cx("badge", theme?.accent, className)} style={style} {...attributes}>
      {text} in {theme?.label ?? "no theme"}
    </span>
  );
}
```

#vue

<!-- prettier-ignore -->
```vue [ThemeProvider.vue]
<script lang="ts">
import type { InjectionKey } from "vue";

export interface Theme {
  accent: string;
  label: string;
}

export const ThemeKey: InjectionKey<Theme> = Symbol("uf.theme");
</script>

<script setup lang="ts">
import Badge from "./Badge.vue";
import { provide } from "vue";

provide(ThemeKey, { accent: "teal", label: "Teal" });
</script>

<template>
  <section aria-label="Themed">
    <Badge text="New" />
  </section>
</template>
```

<!-- prettier-ignore -->
```vue [Badge.vue]
<script setup lang="ts">
import { ThemeKey } from "./ThemeProvider.vue";
import { inject } from "vue";

const { text } = defineProps<{ text: string }>();

const theme = inject(ThemeKey, undefined);
</script>

<template>
  <span class="badge" :class="theme?.accent">{{ text }} in {{ theme?.label ?? "no theme" }}</span>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [ThemeProvider.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts" module>
  export interface Theme {
    accent: string;
    label: string;
  }

  export const ThemeKey = Symbol("uf.theme") as symbol & { readonly __value: Theme };
</script>

<script lang="ts">
  import Badge from "./Badge.svelte";
  import { setContext } from "svelte";
  import type { ClassValue, SvelteHTMLElements } from "svelte/elements";

  type Props = Omit<SvelteHTMLElements["section"], "children" | "class" | "style" | "ref"> & {
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["section"] | null;
  };

  let { class: className, style, ref = $bindable(null), ...attributes }: Props = $props();

  setContext(ThemeKey, { accent: "teal", label: "Teal" });
</script>

<section aria-label="Themed" class={className} {style} bind:this={ref} {...attributes}>
  <Badge text="New" />
</section>
```

<!-- prettier-ignore -->
```svelte [Badge.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import { ThemeKey } from "./ThemeProvider.svelte";
  import { getContext } from "svelte";
  import type { ClassValue, SvelteHTMLElements } from "svelte/elements";

  type Props = Omit<SvelteHTMLElements["span"], "text" | "children" | "class" | "style" | "ref"> & {
    text: string;
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["span"] | null;
  };

  let { text, class: className, style, ref = $bindable(null), ...attributes }: Props = $props();

  const theme = getContext<(typeof ThemeKey)["__value"] | undefined>(ThemeKey);
</script>

<span
  class={["badge", theme?.accent, className]}
  {style}
  bind:this={ref}
  {...attributes}
>{text} in {theme?.label ?? "no theme"}</span>
```

#angular

<!-- prettier-ignore -->
```ts [theme-provider.ts]
import { Fallthrough } from "./_unframework/Fallthrough";
import type { Listeners } from "./_unframework/Listeners";
import { ScopeAttributes } from "./_unframework/ScopeAttributes";
import Badge from "./badge";
import { Component, ElementRef, InjectionToken, inject, input, viewChild } from "@angular/core";

export interface Theme {
  accent: string;
  label: string;
}

export const ThemeKey = new InjectionToken<Theme>("uf.theme");

@Component({
  selector: "uf-theme-provider",
  imports: [Badge, ScopeAttributes, Fallthrough],
  providers: [{ provide: ThemeKey, useValue: { accent: "teal", label: "Teal" } }],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    <section
      aria-label="Themed"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <uf-badge [text]="'New'" />
    </section>
  `,
})
export default class ThemeProvider {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLElement>>("ufElement");
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [badge.ts]
import { Fallthrough } from "./_unframework/Fallthrough";
import type { Listeners } from "./_unframework/Listeners";
import { ScopeAttributes } from "./_unframework/ScopeAttributes";
import { ThemeKey } from "./theme-provider";
import {
  Component,
  ElementRef,
  Injector,
  type OnInit,
  computed,
  inject,
  input,
  untracked,
  viewChild,
} from "@angular/core";

@Component({
  selector: "uf-badge",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let text = this.text();
    @let theme = this.theme();
    <span
      class="badge"
      [class]="[theme?.accent, this.class()].join(' ')"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >{{ text }} in {{ theme?.label ?? "no theme" }}</span>
  `,
})
export default class Badge implements OnInit {
  readonly text = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLSpanElement>>("ufElement");
  private readonly injector = inject(Injector);
  protected readonly theme = computed(() =>
    untracked(
      () => this.injector.get(ThemeKey, null, { optional: true, skipSelf: true }) ?? undefined,
    ),
  );

  ngOnInit(): void {
    // Read once the inputs are set: these keep the values they start with.
    this.theme();
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [ThemeProvider.tsx]
import Badge from "./Badge";
import { type ComponentProps, type JSX, createContext } from "solid-js";

export interface Theme {
  accent: string;
  label: string;
}

export const ThemeKey = createContext<Theme>();

export default function ThemeProvider(
  props: Omit<ComponentProps<"section">, "style"> & { style?: JSX.CSSProperties },
) {
  return (
    <ThemeKey.Provider value={{ accent: "teal", label: "Teal" }}>
      <section aria-label="Themed" {...props}>
        <Badge text="New" />
      </section>
    </ThemeKey.Provider>
  );
}
```

<!-- prettier-ignore -->
```tsx [Badge.tsx]
import { ThemeKey } from "./ThemeProvider";
import { cx } from "./_unframework/cx";
import { type ComponentProps, type JSX, splitProps, useContext } from "solid-js";

export default function Badge(
  props: { text: string } & Omit<ComponentProps<"span">, "text" | "style"> & {
      style?: JSX.CSSProperties;
    },
) {
  const [, others] = splitProps(props, ["text", "class"]);

  const theme = useContext(ThemeKey);

  return (
    <span class={cx("badge", theme?.accent, props.class)} {...others}>
      {props.text} in {theme?.label ?? "no theme"}
    </span>
  );
}
```

#qwik

<!-- prettier-ignore -->
```tsx [ThemeProvider.tsx]
import Badge from "./Badge";
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  component$,
  createContextId,
  useContextProvider,
} from "@qwik.dev/core";

export interface Theme {
  accent: string;
  label: string;
}

export const ThemeKey = createContextId<Theme>("uf.theme");

export default component$<
  Omit<PropsOf<"section">, "class" | "style"> & { class?: ClassList; style?: CSSProperties }
>(({ class: className, style, ...attributes }) => {
  useContextProvider(ThemeKey, { accent: "teal", label: "Teal" });

  return (
    <section aria-label="Themed" class={className} style={style} {...attributes}>
      <Badge text="New" />
    </section>
  );
});
```

<!-- prettier-ignore -->
```tsx [Badge.tsx]
import { ThemeKey } from "./ThemeProvider";
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  component$,
  useContext,
} from "@qwik.dev/core";

export default component$<
  { text: string } & Omit<PropsOf<"span">, "text" | "class" | "style"> & {
      class?: ClassList;
      style?: CSSProperties;
    }
>(({ text, class: className, style, ...attributes }) => {
  const theme = useContext(ThemeKey, (provided?) => provided);

  return (
    <span class={["badge", theme?.accent, className]} style={style} {...attributes}>
      {text} in {theme?.label ?? "no theme"}
    </span>
  );
});
```

#astro

<!-- prettier-ignore -->
```astro [ThemeProvider.astro]
---
import Badge from "./Badge.astro";
import type { HTMLAttributes } from "astro/types";

export interface Theme {
  accent: string;
  label: string;
}

export type ThemeKey = Theme;

interface Props extends HTMLAttributes<"section"> {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style, "aria-label": ariaLabel, ...attrs } = Astro.props;
---

<section
  aria-label={"aria-label" in Astro.props ? ariaLabel : "Themed"}
  class:list={[className]}
  style={style}
  {...attrs}
>
  <Badge text="New" />
</section>
```

<!-- prettier-ignore -->
```astro [Badge.astro]
---
import type { ThemeKey } from "./ThemeProvider.astro";
import type { HTMLAttributes } from "astro/types";

interface Props extends Omit<HTMLAttributes<"span">, "text"> {
  text: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { text, class: className, style, ...attrs } = Astro.props;

const theme = undefined as ThemeKey | undefined;
---

<span
  class:list={["badge", theme?.accent, className]}
  style={style}
  {...attrs}
>{text} in {theme?.label ?? "no theme"}</span>
```

::

- React declares the key with `createContext`, wraps the template in `<ThemeKey value={…}>`, and reads it with `use(ThemeKey)`.
- Vue keeps the `Symbol` in a `<script lang="ts">` block beside `<script setup>`, so that other files can import it. It writes `provide` and `inject`.
- Svelte keeps the `Symbol` in a `<script module>` block, typed with the value it carries. It writes `setContext` and `getContext`.
- Angular declares an `InjectionToken`, lists it in the component's `providers`, and reads it from the parent's injector with `skipSelf`, once its inputs are set.
- Solid declares the key with `createContext`, wraps the template in `<ThemeKey.Provider>`, and reads it with `useContext`.
- Qwik declares the key with `createContextId`, and writes `useContextProvider` and `useContext`.
- Astro renders each component on its own, with no tree of components to provide to, so the key is a type and `inject` gives its fallback ([`context`](/docs/reference/targets#capabilities), a warning).

A key declared as anything but an exported `InjectionKey` `Symbol` is [UF2033](/docs/reference/diagnostics#UF2033). Passing `provide` or `inject` anything but a key, such as a string, is [UF2032](/docs/reference/diagnostics#UF2032), and so is a key from a `.ts` module, which can't import `InjectionKey` from `@uxfront/unframework` either ([UF1204](/docs/reference/diagnostics#UF1204)): keep each key in the `.uf.tsx` module that provides it. Qwik uses the description as its context's id, so two keys with one description collide in one application: give each a namespaced one, `Symbol("acme.theme")`.

## Providing and injecting

`provide(ThemeKey, value)` and `inject(ThemeKey, fallback)` are setup items at the top level ([UF2005](/docs/reference/diagnostics#UF2005)), and their first argument is the key, by its name ([UF2032](/docs/reference/diagnostics#UF2032)). `inject` gives the value of the nearest ancestor that provides the key, or the fallback where none does:

<!-- prettier-ignore -->
```tsx [Greeting.uf.tsx]
import { inject } from "@uxfront/unframework";

import { LocaleKey } from "./LocaleProvider.uf.tsx";

export default function Greeting({ name }: { name: string }) {
  const locale = inject(LocaleKey, "en");
  return (
    <p>
      {locale === "pt" ? "Olá" : "Hello"}, {name} ({locale})
    </p>
  );
}
```

Outside a `LocaleProvider`, `Greeting` says "Hello, Ada (en)", and inside one with `locale="pt"`, "Olá, Inês (pt)". On Astro every `Greeting` gives the fallback.

An injected value is read-only: a write to it, or to one of its members, is [UF2034](/docs/reference/diagnostics#UF2034). It would change the provider's state behind its back on some targets and nothing on others. To let descendants change it, provide a function beside the value, and call it.

## Reactive values

A provided ref or computed stays reactive: a descendant that injects it renders each change.

<!-- prettier-ignore -->
```tsx [Counter.uf.tsx]
import { provide, ref } from "@uxfront/unframework";
import type { InjectionKey, Ref } from "@uxfront/unframework";

import Display from "./Display.uf.tsx";

export const CountKey: InjectionKey<Ref<number>> = Symbol("uf.count");

export default function Counter() {
  const count = ref(1);
  provide(CountKey, count);
  return (
    <section aria-label="Counter">
      <Display />
      <button type="button" onClick={() => (count.value += 1)}>
        Add one
      </button>
    </section>
  );
}
```

<!-- prettier-ignore -->
```tsx [Display.uf.tsx]
import { inject, ref } from "@uxfront/unframework";

import { CountKey } from "./Counter.uf.tsx";

export default function Display() {
  const none = ref(0);
  const count = inject(CountKey, none);
  return <output>Count: {count.value}</output>;
}
```

Vue provides the ref itself, and Qwik its signal. React, Svelte and Angular provide an object with a `value` getter over the state, through an inline helper, `refObject`, and Solid writes the same getter in place, so a descendant reads `count.value` as it changes ([`reactive-context`](/docs/reference/targets#capabilities), emulated). React makes that object again at each render of the provider, so on React code that runs later, after an `await` or in a timer, reads the value of the descendant's last render. On Astro a provided ref reaches no descendant.

## Nested providers

A component may inject a key and provide it too. It reads its parent's value, as Vue does, so its `inject` comes before its `provide` ([UF2032](/docs/reference/diagnostics#UF2032)):

<!-- prettier-ignore -->
```tsx [Level.uf.tsx]
import { defineSlots, inject, provide } from "@uxfront/unframework";
import type { Element, InjectionKey } from "@uxfront/unframework";

export const DepthKey: InjectionKey<number> = Symbol("uf.depth");

export default function Level({ title }: { title: string }) {
  const slots = defineSlots<{ default?(): Element }>();
  const depth = inject(DepthKey, 0);
  provide(DepthKey, depth + 1);
  return (
    <section aria-label={title}>
      <h2>
        {title} at depth {depth}
      </h2>
      {slots.default?.()}
    </section>
  );
}
```

Each `Level` reads its parent's depth and provides its own, so the "Chapter" is at depth 2 and the "Appendix" at depth 1: the nearest provider wins. Angular injects with `skipSelf`, since the component's own `providers` would answer first.

The decisions behind this page are [ADR-0054](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0054-composition-on-every-target.md) and [ADR-0055](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0055-composition-ir-capabilities-and-codes.md).
