In a Blazor component list, what do @key and @ref do, and what goes wrong with duplicate keys or a @ref read before rendering?
answer
- @key maps old to new by value
- scoped to siblings in one parent
- duplicate keys throw InvalidOperationException
- @ref is assigned during rendering
- ElementReference versus a component instance
basics
~20 s@key makes Blazor match list items by a value instead of by position, so each row keeps its own element or component instance; duplicate keys among siblings throw. @ref stores a reference to an element or component instance, which is null until the component has rendered.
solid answer
~50 sBlazor's diff matches siblings by **position** unless they carry `@key`. With `<WorkOrderRow @key="order.Id" Order="order" />`, inserting, removing or re-sorting orders moves the existing `WorkOrderRow` instances (and their focus, expanded state and input text) with their data instead of reusing them for different rows; changing a key on a single element or component forces it to be discarded and rebuilt, which is a way to reset a detail panel. Keys are compared only among siblings in the same parent, and two equal keys there throw `InvalidOperationException` ("More than one sibling ... has the same key value"). `@ref` captures either an `ElementReference` (for an HTML element, mainly to hand to JavaScript) or the component instance, so the parent can call its methods. The field is assigned while rendering, so it is `null` before the first render; and setting the child's parameters through it bypasses rendering and is flagged by `BL0005`.
code
razor · 13 lines@foreach (var order in orders)
{
<WorkOrderRow @key="order.Id" Order="order" />
}
<VehicleEditor @key="selected.Id" Vehicle="selected" />
<MaintenanceGrid @ref="grid" TItem="WorkOrder" Items="orders" />
<button @onclick="() => grid?.ResetPaging()">First page</button>
@code {
private MaintenanceGrid<WorkOrder>? grid;
}go deeper
Know that @key goes on items rendered in a loop and that @ref gives access to an element or child component.
Explain positional versus keyed matching, what state moves with a keyed instance, the duplicate-key exception and why @ref is null before rendering.
Use @key deliberately - stable ids, single-element resets, no keys where rows are stateless - and keep @ref to imperative commands rather than data flow.
Set list-rendering conventions for a large component library so keyed identity bugs and @ref-driven data flow do not spread across teams.
## Why Blazor needs @key After each render Blazor compares the new render tree with the previous one and applies the differences to the DOM (or to component instances). For a list of siblings without keys, the comparison is **positional**: the first new `<WorkOrderRow>` is matched with the first old one, the second with the second, and so on. When an item is inserted at the top or the list is sorted, every existing instance is reused for **different** data. Anything the instance holds that does not come from parameters - an expanded panel, text typed into an input, focus, a running animation, a field set in `OnInitialized` - stays with the position, not with the work order. ## What @key does `@key` is a Razor directive attribute that gives an element or component a **key value**. During the diff Blazor matches siblings by key: - a key present before and after keeps its element or component instance, even if it moved; - a new key creates a new instance; - a key that disappeared disposes its instance. Good key values are model object instances (reference equality) or stable unique identifiers such as a database id (`int`, `string`, `Guid`). The rules from the source and docs: | Rule | Consequence | |---|---| | keys are compared among **siblings in the same parent** only | the same key under two different parents does not clash | | duplicate keys among siblings | `InvalidOperationException`: more than one sibling of the component or element has the same key value; key values must be unique | | changing the key of a single element or component | the old instance is thrown away and a new one is built | | keys cost a little extra work in the diff | add them where preserving instances matters, typically in `foreach` loops | The single-element trick is useful in a fleet app's detail pane: `<VehicleEditor @key="selectedVehicle.Id" Vehicle="selectedVehicle" />` guarantees that selecting another vehicle gives a fresh editor instead of one that kept the previous vehicle's unsaved edits. Even without `@key`, Blazor preserves element and component instances as much as it can; `@key` only gives you control over which data maps to which instance. ## What @ref does `@ref` captures a reference into a field of the component that writes it: - on an **HTML element** (`<input @ref="plateInput" />` with `private ElementReference plateInput;`), it captures an `ElementReference`, an opaque handle mainly passed to JavaScript interop (for example to focus the element); - on a **component** (`<MaintenanceGrid @ref="grid" ... />` with `private MaintenanceGrid<WorkOrder>? grid;`), it captures the component instance, so the parent can call public methods such as `grid.ResetPaging()`. ## Pitfalls with @ref 1. **It is null before the first render.** The reference is assigned while the render tree is applied, so reading it in `OnInitialized`, in a constructor, or in a markup expression evaluated during the same render (`@onclick="grid!.ResetPaging"`) can hit `null`. Use it from event handlers or after rendering has completed. 2. **It is not reactive.** Calling a method on a referenced child changes the child's state but does not by itself render the child; unless that method calls `StateHasChanged`, the change shows only when something else renders the child. 3. **It must not set parameters.** Writing `grid.Items = newItems` bypasses Blazor's parameter flow; the analyzer reports `BL0005` (component parameter should not be set outside of its component), and the parent's next render overwrites the value anyway. Pass data as parameters and use `@ref` only for imperative commands. 4. **It follows instances.** Inside a keyed list, a `@ref` follows the instance that `@key` preserves; without keys, a captured row reference can end up pointing at a row now showing different data.
- Two work orders in the list share the same Id after a bad import. What does the user see when the list renders with @key="order.Id"?The render fails: the diff finds two siblings with the same key and throws `InvalidOperationException` saying more than one sibling has the same key value and key values must be unique. The page or interactive component cannot render until the data is fixed or the list is keyed by something truly unique.
- When is adding @key not worth it?When list items carry no state of their own beyond their parameters - plain text rows, for example - positional reuse produces the same output and `@key` only adds diff work. It pays off when rows are components or inputs with internal state, focus or animations, or when items are inserted, removed or reordered rather than only appended.
- Without @key Blazor throws away and recreates every list row on each render.
- @key values must be unique across the whole page, not just among siblings.
- A @ref field can be used in OnInitialized because Blazor assigns it before rendering.
- Setting a child's parameters through its @ref is the recommended way to push new data down.
- Duplicate @key values are ignored and Blazor falls back to matching by position.