# 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 CSSProperties, createContext, useState } from "react";

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

export interface ThemeProviderAttributes {
  className?: string;
  style?: CSSProperties;
}

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}
        {...scopeAttributes(attributes)}
      >
        <Badge text="New" />
      </section>
    </ThemeKey>
  );
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

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

export interface BadgeAttributes {
  className?: string;
  style?: CSSProperties;
}

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}
      {...scopeAttributes(attributes)}
    >
      {text} in {theme?.label ?? "no theme"}
    </span>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#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 } from "svelte/elements";

  type Props = { class?: ClassValue; style?: string };

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

  setContext(ThemeKey, { accent: "teal", label: "Teal" });

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

<section aria-label="Themed" class={className} {style} {...scopeAttributes(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 } from "svelte/elements";

  type Props = { text: string; class?: ClassValue; style?: string };

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

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

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

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

#angular

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

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

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

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

@Component({
  selector: "uf-theme-provider",
  imports: [Badge, ScopeAttributes],
  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()"
      [ufScope]="this.host"
    >
      <uf-badge [text]="'New'" />
    </section>
  `,
})
export default class ThemeProvider {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

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

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

@Component({
  selector: "uf-badge",
  imports: [ScopeAttributes],
  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()"
      [ufScope]="this.host"
    >{{ 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>>();
  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 JSX, createContext } from "solid-js";

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

export const ThemeKey = createContext<Theme>();

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

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

export default function Badge(
  props: { text: string } & { class?: string; style?: JSX.CSSProperties },
) {
  const theme = useContext(ThemeKey);

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

/** Joins class names: strings as they are, and the names of an object's truthy entries. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") names.push(part);
    else if (part && typeof part === "object") {
      for (const [name, on] of Object.entries(part)) if (on) names.push(name);
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

#qwik

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

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

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

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

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

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

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

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#astro

<!-- prettier-ignore -->
```astro [ThemeProvider.astro]
---
import Badge from "./Badge.astro";

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

export type ThemeKey = Theme;

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

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
---

<section
  aria-label="Themed"
  class:list={[className]}
  style={style}
  {...scopeAttributes(Astro.props)}
>
  <Badge text="New" />
</section>
```

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

interface Props {
  text: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}

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

<span
  class:list={["badge", theme?.accent, className]}
  style={style}
  {...scopeAttributes(Astro.props)}
>{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).
