In Blazor, how do StateHasChanged, ShouldRender and the render tree diff decide what a component sends to the DOM, and when is overriding ShouldRender worth it?
answer
- one queued render per component
- ShouldRender ignored on the first render
- BuildRenderTree, then diff with the old tree
- sequence numbers from source lines
- a RenderBatch of DOM edits
basics
~20 sStateHasChanged queues one render unless one is already pending; ShouldRender can veto it except on the first render. A render rebuilds the component's render tree and diffs it against the previous one, so only changed elements, attributes and text are sent as DOM edits.
solid answer
~50 s`StateHasChanged()` does nothing if the component already has a render queued, so five calls in a row produce one render. Otherwise it consults `ShouldRender()` - ignored for the very first render - and queues the render. Rendering runs `BuildRenderTree`, which the Razor compiler generated from the markup, producing a new **render tree** of frames tagged with **sequence numbers** taken from source positions. The renderer diffs the new tree against the previous one in linear time, matching frames by sequence number (and `@key`), and produces a `RenderBatch` of edits: changed text, attributes, inserted or removed elements, and child components whose parameters may have changed. Interactive Server sends that batch over the circuit; WebAssembly applies it in the browser. Overriding `ShouldRender` pays off when frequent events or parameter updates change state the markup does not show; the cost is stale UI if the condition is wrong.
code
razor · 26 lines<p>Hour @shownHour:00 - @temperature °C</p>
@code {
[Parameter] public SensorReading? Reading { get; set; }
private int shownHour = -1;
private double temperature;
private bool hourChanged;
protected override void OnParametersSet()
{
if (Reading is not null && Reading.At.Hour != shownHour)
{
shownHour = Reading.At.Hour;
temperature = Reading.Celsius;
hourChanged = true;
}
}
protected override bool ShouldRender()
{
var render = hourChanged;
hourChanged = false;
return render;
}
}go deeper
Know that StateHasChanged asks Blazor to re-render and that only the changed parts of the page are updated.
Explain queued renders, the first-render exception to ShouldRender, and what the render tree diff sends as a RenderBatch.
Use ShouldRender and parameter design to cut renders on hot paths, explain sequence numbers and keys in the diff, and avoid stale UI from wrong conditions.
Decide where render-cost optimisation is justified by measurement across an app, and keep the default rendering model elsewhere for simplicity.
## From StateHasChanged to a render In Blazor a component never touches the DOM directly. It describes its output, and the renderer works out the changes. The path for a `ComponentBase` component is: 1. **`StateHasChanged()`** is called - by you, or automatically after lifecycle methods and event handlers. 2. If a render is **already queued** for this component, the call returns immediately. The docs' example: calling it five times in a loop renders once. 3. Otherwise `ComponentBase` checks: is this the first render, or does **`ShouldRender()`** return `true`? (A hot-reload metadata update also forces a render.) If neither, nothing is queued. 4. The renderer runs the component's **`BuildRenderTree`** method - generated by the Razor compiler from the `.razor` markup - producing a new **render tree**: a flat array of frames (elements, attributes, text, child components, regions). 5. The renderer **diffs** the new tree against the component's previous one. 6. Edits are collected into a **`RenderBatch`**, together with the edits of any child components that re-rendered, and applied to the UI: Interactive Server serializes the batch over the circuit's connection, WebAssembly applies it to the DOM in the browser. 7. After the UI has been updated, `OnAfterRender{Async}` runs. ## How the diff stays cheap General tree diffing is expensive; Blazor makes it linear by using **sequence numbers**. Each frame carries the number of the source position that produced it, assigned at compile time. When the diff walks the old and new frame arrays together, equal sequence numbers mean "same line of code", so it can tell inserted and removed `if` branches or loop items from changed ones without searching. `@key` refines the matching for loop items. For **child components** the diff reuses the existing instance and calls its `SetParametersAsync` only if the parameters may have changed - an object-typed parameter always counts as possibly changed, while unchanged primitives do not. Hand-written `RenderTreeBuilder` code must hardcode sequence numbers as literals; the docs warn that generating them with a counter destroys the information the diff relies on and makes diffs much longer. Prefer `.razor` markup, and use `OpenRegion`/`CloseRegion` around manual blocks. ## When overriding ShouldRender helps | Situation | Worth overriding? | |---|---| | an `oninput` handler updates a field the markup does not display until submit | yes - skip renders while typing | | a sensor feed updates state every second but the widget shows hourly values | yes - render only when the hour changes | | a large table re-rendered by every parent render with unchanged data | yes, with a cheap check such as a version number | | an ordinary component with a few events | no - the default `true` is correct and simpler | Things to keep in mind: - `ShouldRender` is **ignored for the first render**: a component always renders once. - Returning `false` also skips the after-render calls for that render. - A child that handles its own events still re-renders itself; `ShouldRender` on the parent does not freeze the subtree. - A wrong condition shows stale data with no error, so keep the check simple and test it. ## What re-renders without StateHasChanged `ComponentBase` already re-renders after parameters are applied, after a cascading value it subscribes to changes, after its own event handlers and `EventCallback`s (twice for async handlers), and after `OnInitializedAsync`/`OnParametersSetAsync`. Explicit `StateHasChanged` calls are needed mainly for changes that come from outside those paths - timers, service events - and those must go through `InvokeAsync`.
- An event handler sets count++, calls StateHasChanged, then sets count++ again. What does the UI show after a click on value 0?It shows 2. `StateHasChanged` only queues a render; the render runs when the handler's synchronous work has finished, so it sees both increments. The automatic render after the handler finds a render already queued and does not add another.
- Why does generating RenderTreeBuilder sequence numbers with a counter hurt performance?The diff assumes equal sequence numbers mean the same source location. A counter numbers frames by execution order, so when an `if` branch appears or disappears every later frame shifts and no longer lines up with the old tree; the diff then sees many changes instead of one insertion, producing much larger render batches.
- Calling StateHasChanged five times in a row renders the component five times.
- Returning false from ShouldRender also prevents the component's very first render.
- Blazor re-sends the whole component's HTML to the browser on every render.
- Sequence numbers are assigned at runtime from the order frames are added.
- ShouldRender returning false on a parent freezes all of its child components.