In this lesson, you will learn how to reduce layout thrashing in Blazor by optimizing your component render hierarchy to prevent unnecessary DOM updates.
The Problem: Layout Thrashing
Layout thrashing occurs when the browser is forced to perform multiple reflows—calculating the geometry and position of elements—in a single frame. In Blazor, this often happens when a parent component triggers a re-render that forces all of its children to re-evaluate their own render trees, even if their underlying data hasn't changed. If those children then attempt to measure their own DOM dimensions (via JavaScript Interop) while the layout is invalid, the browser must pause execution to recalculate, causing jittery UI performance.
Optimizing the Hierarchy
The goal is to keep the "render blast radius" as small as possible. Instead of having a single monolithic component that manages state for the entire page, decompose your UI into granular components that manage their own local state.
By implementing ShouldRender(), you can explicitly tell Blazor when a component should skip the diffing process entirely.
@code {
[Parameter] public string Data { get; set; }
private string _lastData;
protected override bool ShouldRender()
{
// Only re-render if the relevant data has actually changed
if (Data != _lastData)
{
_lastData = Data;
return true;
}
return false;
}
}
Strategic Placement of State
Another common performance killer is placing state at the top of a deep component tree. When that state changes, the entire tree re-renders. To optimize this, "push" the state down. If only a small leaf component needs the data, pass it as a parameter directly to that component, or use a scoped service/event bus to notify only the interested subscribers. By isolating the components that actually need to react to changes, you prevent the browser from needing to traverse and re-calculate the layout of stable, static parts of your UI.
Key Takeaway: Reduce layout thrashing by isolating state to the lowest possible component level and using ShouldRender() to prune unnecessary branches from the render tree.