{"slug":"coordinate-components","title":"coordinate-components","summary":"Share state between components that don't have a direct parent-child parameter relationship, using cascading values, scoped services with change events, or CascadingValueSource via DI. USE WHEN the user needs a CascadingParameter or CascadingValue that works across render mode bo","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-08-24T05:37:36.841476Z","repo":{"url":"https://github.com/dotnet/skills","stars":6296,"forks":500,"license":"MIT","updatedAt":"2026-11-19T18:23:42Z"},"bodyHtml":"<hr>\n<h2>license: MIT\nname: coordinate-components\ndescription: &gt;\nShare state between components that don't have a direct parent-child parameter relationship,\nusing cascading values, scoped services with change events, or CascadingValueSource via DI.\nUSE WHEN the user needs a CascadingParameter or CascadingValue that works across render mode\nboundaries, a shopping cart or notification count accessible from multiple pages, a theme or\nuser preference cascaded app-wide, or when components in different parts of the tree must\nreact when shared data changes. Also USE WHEN cascading values aren't reaching interactive\nchildren in per-page interactivity mode, or when the user needs to understand scoped vs\nsingleton service lifetime for state on Blazor Server.\nDO NOT USE for direct parent-child parameter passing or EventCallback (see author-component),\nfor persisting state across prerender-to-interactive transitions (see support-prerendering),\nor for service abstractions for data fetching in Auto/WebAssembly (see fetch-and-send-data).</h2>\n<h1>Coordinate Components</h1>\n<h2>Step 1 — Read AGENTS.md</h2>\n<p>Read <code>AGENTS.md</code> at the workspace root to learn the project's conventions before making changes.</p>\n<h2>Step 2 — Decide the scope</h2>\n<table>\n<thead>\n<tr>\n<th>Need</th>\n<th>Mechanism</th>\n<th>When to use</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Subtree (same render mode)</td>\n<td><code>CascadingValue</code> component</td>\n<td>Theme, layout config within a layout</td>\n</tr>\n<tr>\n<td>App-wide (all render modes)</td>\n<td><code>CascadingValueSource&lt;T&gt;</code> via DI</td>\n<td>Current user, feature flags, theme shared globally</td>\n</tr>\n<tr>\n<td>Mutable shared state within a circuit</td>\n<td>Scoped service + <code>Action</code> event</td>\n<td>Shopping cart, notification count, selected filters</td>\n</tr>\n</tbody>\n</table>\n<p>For parent→child one level: use <code>[Parameter]</code> / <code>EventCallback</code> (see <code>author-component</code> skill).\nFor persisting state across prerender→interactive: see <code>support-prerendering</code> skill.</p>\n<h2>Workflow (quick reference)</h2>\n<ol>\n<li>Choose the mechanism from the table in Step 2</li>\n<li>If crossing render mode boundaries → use <code>CascadingValueSource&lt;T&gt;</code> (Step 4)</li>\n<li>Register in <code>Program.cs</code> with <code>AddCascadingValue(...)</code> and <code>isFixed: false</code></li>\n<li>Consume via <code>[CascadingParameter]</code> in child components</li>\n<li>Update via <code>NotifyChangedAsync(newValue)</code> — never page reload</li>\n<li>For additional mutable state within a circuit → add scoped service (Step 5)</li>\n<li>Wrap any <code>StateHasChanged</code> from background threads in <code>InvokeAsync</code></li>\n<li>Implement <code>IDisposable</code> — dispose timers, cancel tokens, unsubscribe events</li>\n</ol>\n<h2>Step 3 — CascadingValue for subtree state</h2>\n<p>Wrap a subtree with <code>&lt;CascadingValue&gt;</code> to flow data to all descendants without passing it through every intermediate component.</p>\n<pre><code>@* In a layout or parent component *@\n&lt;CascadingValue Value=\"theme\"&gt;\n    @Body\n&lt;/CascadingValue&gt;\n\n@code {\n    private ThemeInfo theme = new() { ButtonClass = \"btn-primary\" };\n}\n</code></pre>\n<p>Consume in any descendant:</p>\n<pre><code>[CascadingParameter]\nprivate ThemeInfo? Theme { get; set; }\n</code></pre>\n<p><strong>Rules:</strong></p>\n<ul>\n<li>Matched by <strong>type</strong>, not name. To cascade multiple values of the same type, add <code>Name</code>:\n<pre><code>&lt;CascadingValue Value=\"primary\" Name=\"PrimaryTheme\"&gt;...&lt;/CascadingValue&gt;\n</code></pre>\n<pre><code>[CascadingParameter(Name = \"PrimaryTheme\")]\nprivate ThemeInfo? Primary { get; set; }\n</code></pre>\n</li>\n<li>Set <code>IsFixed=\"true\"</code> when the value never changes — avoids subscription overhead.</li>\n<li><strong>Does NOT cross render mode boundaries.</strong> A <code>&lt;CascadingValue&gt;</code> in a static SSR parent is invisible to interactive children. See Step 6.</li>\n</ul>\n<h2>Step 4 — CascadingValueSource&lt;T&gt; for app-wide state</h2>\n<p>Register a <code>CascadingValueSource&lt;T&gt;</code> in DI when the value must be available to <strong>all components regardless of render mode</strong>.</p>\n<pre><code>// Program.cs\nbuilder.Services.AddCascadingValue(sp =&gt;\n{\n    var theme = new ThemeInfo { ButtonClass = \"btn-primary\" };\n    return new CascadingValueSource&lt;ThemeInfo&gt;(theme, isFixed: false);\n});\n</code></pre>\n<p>Consume identically to Step 3:</p>\n<pre><code>[CascadingParameter]\nprivate ThemeInfo? Theme { get; set; }\n</code></pre>\n<p><strong>To update and notify subscribers</strong>, either mutate the existing object or replace it:</p>\n<pre><code>@* Component that changes the theme *@\n@inject CascadingValueSource&lt;ThemeInfo&gt; ThemeSource\n\n&lt;button @onclick=\"ToggleDarkMode\"&gt;Toggle theme&lt;/button&gt;\n\n@code {\n    private bool isDark;\n\n    private async Task ToggleDarkMode()\n    {\n        isDark = !isDark;\n        // Replace the value entirely:\n        var newTheme = new ThemeInfo { ButtonClass = isDark ? \"btn-dark\" : \"btn-primary\" };\n        await ThemeSource.NotifyChangedAsync(newTheme);\n    }\n}\n</code></pre>\n<p><code>NotifyChangedAsync()</code> (no argument) also works — mutate the object and then call it. <code>NotifyChangedAsync(newValue)</code> replaces the value and notifies in one step.</p>\n<p><strong>Update protocol:</strong> Whenever shared state changes, the component that changes it MUST inject <code>CascadingValueSource&lt;T&gt;</code> and call <code>NotifyChangedAsync()</code>. This is the only mechanism that triggers re-rendering in all <code>[CascadingParameter]</code> subscribers. Without this call, no subscribers update. Do not use <code>NavigationManager.Refresh()</code> or page reloads as a substitute.</p>\n<p><strong>Rules:</strong></p>\n<ul>\n<li><code>isFixed: false</code> enables change notifications. <code>isFixed: true</code> is better for truly static values (feature flags).</li>\n<li><strong>Crosses render mode boundaries</strong> — works for per-page interactivity, global interactivity, and WebAssembly. Key advantage over <code>&lt;CascadingValue&gt;</code>.</li>\n<li>Keep cascaded types <strong>granular</strong>. Every <code>NotifyChangedAsync</code> re-renders ALL subscribers regardless of which property changed. Don't put all app state into one cascaded type.</li>\n<li>For Auto/WebAssembly apps, register in <strong>both</strong> server and <code>.Client</code> <code>Program.cs</code>. The type must be in a shared assembly.</li>\n</ul>\n<h2>Step 5 — Scoped state service with change events</h2>\n<p>For mutable shared state that multiple components read <strong>and write</strong> (shopping cart, notification count, filters), use a scoped service with an event for change notification.</p>\n<p><strong>Define the service:</strong></p>\n<pre><code>public class CartState\n{\n    private readonly List&lt;CartItem&gt; _items = [];\n\n    public IReadOnlyList&lt;CartItem&gt; Items =&gt; _items;\n    public int Count =&gt; _items.Count;\n\n    public event Action? OnChange;\n\n    public void Add(CartItem item)\n    {\n        _items.Add(item);\n        OnChange?.Invoke();\n    }\n\n    public void Remove(CartItem item)\n    {\n        _items.Remove(item);\n        OnChange?.Invoke();\n    }\n}\n</code></pre>\n<p><strong>Register as scoped:</strong></p>\n<pre><code>builder.Services.AddScoped&lt;CartState&gt;();\n</code></pre>\n<p><strong>Subscribe in components:</strong></p>\n<pre><code>@inject CartState Cart\n@implements IDisposable\n\n&lt;span class=\"badge\"&gt;@Cart.Count&lt;/span&gt;\n\n@code {\n    protected override void OnInitialized()\n    {\n        Cart.OnChange += StateHasChanged;\n    }\n\n    public void Dispose()\n    {\n        Cart.OnChange -= StateHasChanged;\n    }\n}\n</code></pre>\n<p>The simple <code>Action OnChange</code> pattern works when the event fires from the Blazor sync context (button click → <code>Cart.Add(…)</code>). If the event fires from <strong>outside</strong> the sync context (timer, background task, SignalR hub), wrap in <code>InvokeAsync</code>:</p>\n<pre><code>private Action? _handler;\n\nprotected override void OnInitialized()\n{\n    _handler = () =&gt; InvokeAsync(StateHasChanged);\n    Cart.OnChange += _handler;\n}\n\npublic void Dispose() =&gt; Cart.OnChange -= _handler;\n</code></pre>\n<p>Store the delegate in a field so you can unsubscribe the exact same instance.</p>\n<h2>Step 6 — Render mode and service lifetime rules</h2>\n<h3>Cascading values don't cross render mode boundaries</h3>\n<p>A <code>&lt;CascadingValue&gt;</code> placed in a static SSR layout (<code>MainLayout.razor</code> when the layout renders statically) will <strong>not</strong> reach interactive children. The interactive component sees <code>null</code> for the cascading parameter.</p>\n<p><strong>Fix:</strong> Use <code>CascadingValueSource&lt;T&gt;</code> registered in DI (Step 4) or a scoped service (Step 5). Both cross boundaries because DI services are resolved per-circuit, not from the component tree.</p>\n<h3>Service lifetime on Server vs WebAssembly</h3>\n<table>\n<thead>\n<tr>\n<th>Lifetime</th>\n<th>Server</th>\n<th>WebAssembly</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Scoped</strong></td>\n<td>Per circuit (per user connection)</td>\n<td>Per browser tab</td>\n</tr>\n<tr>\n<td><strong>Singleton</strong></td>\n<td>Shared across ALL users</td>\n<td>Per browser tab (safe)</td>\n</tr>\n<tr>\n<td><strong>Transient</strong></td>\n<td>New instance per injection</td>\n<td>New instance per injection</td>\n</tr>\n</tbody>\n</table>\n<p>On Server, <strong>never store user-specific state in a singleton</strong> — every user's circuit shares the same singleton. One user's cart leaks into another's. Use <code>AddScoped&lt;T&gt;()</code>.</p>\n<p>On WebAssembly, singletons are per-tab and safe. But code meant for <strong>both</strong> Server and WebAssembly (Auto mode) must use scoped.</p>\n<h3>Auto/WebAssembly with prerendering</h3>\n<p>State services must be defined in the <code>.Client</code> project or a shared assembly — they cannot reference server-only types. Register the service in both <code>Program.cs</code> files. State created during prerender does not survive the switch to the interactive runtime. Use the <code>support-prerendering</code> skill's <code>[PersistentState]</code> pattern to carry state across.</p>\n<h2>Don'ts</h2>\n<ul>\n<li><strong>Don't use a singleton for per-user state on Server</strong> — all circuits share it, leaking state between users.</li>\n<li><strong>Don't put all app state into one cascaded object</strong> — <code>NotifyChangedAsync</code> re-renders ALL subscribers on every change. Separate concerns into distinct types (<code>ThemeState</code>, <code>CartState</code>, <code>UserPreferences</code>).</li>\n<li><strong>Don't forget to unsubscribe</strong> — omitting <code>Dispose</code> on event subscriptions causes memory leaks that grow per-circuit.</li>\n<li><strong>Don't use <code>&lt;CascadingValue&gt;</code> in a static layout expecting it to reach interactive children</strong> — it won't cross render mode boundaries. Use DI-registered <code>CascadingValueSource&lt;T&gt;</code> or scoped services.</li>\n<li><strong>Don't use <code>NavigationManager.Refresh(forceReload: true)</code> to propagate cascading value changes</strong> — this destroys the circuit and forces a full page reload. Instead, inject <code>CascadingValueSource&lt;T&gt;</code> and call <code>NotifyChangedAsync(newValue)</code> to push updates to all <code>[CascadingParameter]</code> subscribers without a page reload.</li>\n<li><strong>Don't call <code>StateHasChanged</code> from a non-Blazor thread</strong> — wrap in <code>InvokeAsync</code>. The framework throws <code>InvalidOperationException: The current thread is not associated with the Dispatcher</code>.</li>\n</ul>\n","files":[{"path":"SKILL.md","sizeBytes":9980,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-08-24T05:42:02.923229Z","sha256":"9122669772A86CA774028DEF7E6E37733D45B240E7C6D6F6BDDE096905C920E6","sizeBytes":3908},"review":null,"source":{"repositoryUrl":"https://github.com/dotnet/skills","path":"plugins/dotnet-blazor/skills/coordinate-components","license":"MIT","commit":"4e03bfdade5d1f9b7d1c2e95f64e31d1cb7af5ab","subtreeSha":"0710EB6919AA4DB72B24E73F3834E0AE95EEF8A154588238552B936847FD8E96","lastSyncedAt":"2026-11-19T19:30:03.195544Z"},"reviewedAt":"2026-08-24T05:53:23.160211Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/dotnet/skills/tree/main/plugins/dotnet-blazor/skills/coordinate-components"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install dotnet-skills@llmmart"},{"target":"git","command":"git clone https://github.com/dotnet/skills.git"}]}