brumate

Context

A context passes a value from a component to every component inside it, without props. It suits values that many components read, such as a theme, the current user or a language.

Edit the code to run it again

The sample runs when it comes into view.

Badge reads the theme two components down, and Toolbar in between knows nothing about it.

Creating a context

createContext(key, defaultValue) from brumate/context creates a context. Put it in a .ts file, so the components that provide and read it can import it.

import { createContext } from 'brumate/context';

export const Locale = createContext<string>('locale', 'en');

Providing a value

$setContext(context, value) gives the components inside this one a value of the context:

let locale = $signal('fr');
$setContext(Locale, locale);

Reading a value

$getContext(context) reads the value from the nearest component above that provides it:

const locale = $getContext(Locale);

Changing a provided value

A component cannot assign to a value that it reads from a context. The component that provides it can give functions that change it, and any component below can call them:

Edit the code to run it again

The sample runs when it comes into view.