skip to content

In a Blazor weather widget, why does chart setup belong in OnAfterRenderAsync guarded by firstRender, and what happens if that method calls StateHasChanged unconditionally?

level: middleimportance: should knowfreq 52%

answer

  1. runs after the UI has updated
  2. @ref fields are populated by then
  3. firstRender is true once per instance
  4. no automatic render after its Task
  5. an unguarded StateHasChanged loops

basics

~20 s

OnAfterRenderAsync runs only after an interactive render has reached the UI, so the chart's element exists; firstRender limits one-time setup to the first call. Calling StateHasChanged there without a guard triggers another render and another OnAfterRenderAsync, an endless render loop.

solid answer

~40 s

`OnAfterRender(bool firstRender)` and `OnAfterRenderAsync(bool firstRender)` run after each render that has been applied to the live UI, so element references captured with `@ref` are set and the DOM exists for JavaScript to draw into. They do **not** run during prerendering or static SSR, which is why setup there is safe from server-side passes. `firstRender` is `true` only on the first call for the component instance, so one-time work - creating the chart - goes inside `if (firstRender)`, while later calls can update it. `ComponentBase` deliberately does **not** re-render when the task from `OnAfterRenderAsync` completes, because that would loop. If you call `StateHasChanged()` there on every call, each render schedules another render, which calls `OnAfterRenderAsync` again: an infinite render loop. Guard it with `firstRender` or a flag, and keep data loading in `OnInitializedAsync`/`OnParametersSetAsync`.

code

razor · 23 lines
razor
@inject IJSRuntime JS

<canvas @ref="canvas"></canvas>

@code {
    [Parameter] public Forecast? Forecast { get; set; }
    private ElementReference canvas;
    private Forecast? drawn;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync("farmCharts.create", canvas);
        }

        if (Forecast is not null && !ReferenceEquals(Forecast, drawn))
        {
            drawn = Forecast;
            await JS.InvokeVoidAsync("farmCharts.draw", canvas, Forecast.Hourly);
        }
    }
}

go deeper

for a junior

Know that DOM- or JavaScript-dependent setup goes in OnAfterRenderAsync inside if (firstRender).

for a middle

Explain when the method runs and does not run, why @ref values are set by then, and why there is no automatic re-render afterwards.

for a senior

Spot render loops and late data loads in OnAfterRenderAsync, and structure one-time setup, per-render updates and guarded state changes correctly.

for a principal

Establish a rule that after-render code is for UI integration only, keeping data loading in the initialization methods so pages prerender and render predictably.

## What OnAfterRender is for `ComponentBase` calls `OnAfterRender(bool firstRender)` and then `OnAfterRenderAsync(bool firstRender)` **after a render has been applied to the UI** - on Interactive Server once the browser has applied the render batch, on WebAssembly once the DOM has been updated. By then: - every element referenced with `@ref` has its `ElementReference` populated; - every child component rendered in that batch exists; - the DOM nodes the component produced are in the page. That makes it the only lifecycle point where a farm dashboard's `WeatherWidget` can hand its `<canvas>` to a JavaScript charting library. (How the JavaScript call itself is made, and how its objects are disposed, is the JS interop topic.) ## When it does not run - **Static SSR** and **prerendering** never call it: those passes produce HTML on the server with no live DOM attached, and they are finished before any browser updates. - A render skipped because `ShouldRender()` returned `false` produces no after-render call. So a prerendered interactive widget gets its first `OnAfterRenderAsync(true)` only after the circuit or the WebAssembly runtime renders it interactively, on the new instance. ## firstRender `firstRender` is `true` on the first call for the **component instance** and `false` afterwards. Use it to separate: 1. one-time setup - creating the chart, attaching a resize observer, focusing an input; 2. per-render work - pushing new data into an already created chart when the forecast changed. ## Why there is no automatic re-render, and the loop trap Unlike event handlers and `OnInitializedAsync`, `OnAfterRenderAsync`'s returned task is awaited **without** a follow-up `StateHasChanged`. The source comments explain: re-rendering after it would cause an infinite loop, and the async overload exists only so developers can start async work without `async void`. The loop appears when developers add the render themselves: | Code in `OnAfterRenderAsync` | Outcome | |---|---| | `await JS...; StateHasChanged();` on every call | render, after-render, render, after-render... forever, burning CPU (and, on the server, the circuit's bandwidth) | | `if (firstRender) { await LoadFromBrowserStorage(); StateHasChanged(); }` | one extra render after the first; correct | | `if (chartNeedsUpdate) { chartNeedsUpdate = false; await UpdateChart(); }` | per-render work without a render request; correct | The legitimate reason to call `StateHasChanged` from `OnAfterRenderAsync` is data that is only available after rendering - something read through JavaScript, such as browser storage - and that call must be guarded. ## Where data loading belongs Loading the forecast in `OnAfterRenderAsync` is a common mistake: it delays the request until after the first render, forces an extra render to show the result, and the data is never part of a prerendered page. Load in `OnInitializedAsync`, or in `OnParametersSetAsync` when it depends on a parameter such as `FieldId`; keep `OnAfterRenderAsync` for work that needs the rendered UI. ## Exceptions An exception thrown from `OnAfterRenderAsync` is treated like any lifecycle exception: an enclosing `ErrorBoundary` shows its error content, and without one the error is unhandled for the circuit or the WebAssembly app.

  • Why does OnAfterRenderAsync(firstRender: true) never fire for a component rendered with static SSR?
    Static SSR renders the component to HTML on the server and discards it; no live DOM is attached and the component never renders interactively, so there is no render after which to call it. `OnAfterRender{Async}` is skipped during static SSR and prerendering and runs only for interactive renders.
  • A widget must read a saved unit preference from browser storage before showing temperatures. How do you structure it?
    Render a neutral state first. In `OnAfterRenderAsync`, inside `if (firstRender)`, read the preference through JavaScript interop, store it in a field and call `StateHasChanged()` once. The guard makes it a single extra render; without it, every render would read storage and request another render.

  • OnAfterRenderAsync re-renders the component automatically when its Task completes.
  • firstRender is true on the first render of every page navigation, even for the same instance.
  • OnAfterRender runs during prerendering, so the chart is ready when the HTML arrives.
  • Calling StateHasChanged at the end of every OnAfterRenderAsync call is harmless.
  • OnAfterRenderAsync is the best place to load the forecast from the API.