Creating a provider
Providers share a typed value with a subtree without threading props through every component. They are transparent nodes: no box, no selector match, just a context scope around their children.
Define a context
A context is a static, strongly typed key with a default value. Put it in a static class so the provider and consumers use the same instance.
using Donkeh.UILab;
namespace MyApp;
public sealed record Theme(string Accent, string Background);
public static class ThemeContext
{
public static readonly Context<Theme> Value = new(
new Theme("#5957d9", "#ffffff"));
public static readonly Theme Dark = new("#9a97ff", "#0b1018");
}
Publish a value
Call Provider(context, value, children...) around the subtree
that should see the value. The provider is transparent, so its children
occupy its slot in the parent.
using Donkeh.UILab;
using static Donkeh.UILab._;
public sealed class App : Component
{
public override Node Render()
{
var (dark, setDark) = State(false);
var theme = dark ? ThemeContext.Dark : ThemeContext.Value.DefaultValue;
return Provider(ThemeContext.Value, theme,
H("main", new Props { ClassName = "app" },
H("button", new Props
{
ClassName = "theme-toggle",
OnClick = () => setDark(!dark)
}, Text(dark ? "Use light theme" : "Use dark theme")),
C<Toolbar>()));
}
}
Consume it
Read the nearest value with UseContext during render. If no
provider is in scope, the context's default is returned.
using Donkeh.UILab;
using static Donkeh.UILab._;
public sealed class Toolbar : Component
{
public override Node Render()
{
var theme = UseContext(ThemeContext.Value);
return H("div", new Props
{
ClassName = "toolbar",
Attributes = new Dictionary<string, string>
{
["style"] = $"background:{theme.Background};color:{theme.Accent}"
}
},
Text("Toolbar"));
}
}
Provider rules
| Rule | Behaviour |
|---|---|
| Nesting | A provider inside another provider for the same context shadows the outer value. |
| Defaults | Consumers outside every provider receive Context<T>.DefaultValue. |
| Scope capture | A component keeps the context scope it rendered under, so a later re-render does not silently change its view of the value. |
| Updates | A provider is rebuilt when its parent renders. Put the state that controls the value above the provider. |
| Layout | Providers generate no box and do not match selectors; children are spliced into the parent. |
App example.
Multiple contexts
Nest providers when a subtree needs more than one value. Consumers read each context independently:
return Provider(ThemeContext.Value, theme,
Provider(LocaleContext.Value, locale,
C<Dashboard>()));