📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Walk me through how a Blazor component works. How do parameters, EventCallback and cascading parameters pass data, what is the order of the lifecycle methods, when does a component re-render, and when do you need to call StateHasChanged yourself?

Covers Blazor component parameters, EventCallback, ChildContent and cascading parameters, the lifecycle order (SetParametersAsync, OnInitialized, OnParametersSet, OnAfterRender, Dispose), the render cycle and when StateHasChanged is needed.

Intermediate Theory Intermediate blazor components frontend lifecycle razor statehaschanged

🎯 Key points

  • [Parameter] properties are set by the parent; never mutate them inside the child
  • EventCallback<T> raises events to the parent and triggers the parent's re-render automatically
  • Lifecycle: SetParametersAsync -> OnInitialized{Async} (once) -> OnParametersSet{Async} -> render -> OnAfterRender{Async}(firstRender)
  • ComponentBase renders after event handlers and lifecycle methods; for async ones it renders when the returned Task is incomplete (it yielded) and again when it completes
  • Call InvokeAsync(StateHasChanged) yourself for timers, background work or service events
  • Children with complex-type parameters re-render whenever the parent re-renders; use ShouldRender, @key or primitive parameters
  • JS interop only in OnAfterRenderAsync; dispose subscriptions with IDisposable/IAsyncDisposable

⏱ 30-second answer

A Blazor component is a class that renders a render tree; Blazor diffs it against the last one and patches the DOM. Parents pass data down with [Parameter] properties and RenderFragment ChildContent, and children raise events up with EventCallback<T>. Ancestors can share values with [CascadingParameter].

The lifecycle is SetParametersAsync β†’ OnInitialized{Async} (once) β†’ OnParametersSet{Async} (every time parameters arrive) β†’ render β†’ OnAfterRender{Async}(firstRender) β†’ Dispose. Blazor calls StateHasChanged for you after event handlers and async lifecycle methods. You only call it yourself, through InvokeAsync(StateHasChanged), when state changes outside Blazor's knowledge: a timer, a background task or a service event. The trade-off is simplicity against wasted renders on big trees.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"A component is a C# class, usually written in Razor, that describes UI as a render tree. When it renders, Blazor compares the new tree with the previous one and sends only the differences to the DOM, locally in WebAssembly or over the circuit in Server mode. Data flows down through [Parameter] properties, including RenderFragment ChildContent for markup, and events flow up through EventCallback<T>. For things many levels need, such as the current user or a theme, an ancestor provides a cascading value and descendants receive it with [CascadingParameter].

The lifecycle runs SetParametersAsync, then OnInitialized or OnInitializedAsync once, then OnParametersSet every time the parent passes parameters, then the render, then OnAfterRender with a firstRender flag. OnAfterRenderAsync(firstRender: true) is the only safe place for JavaScript interop, because the DOM elements exist. At the end, Dispose or DisposeAsync is where I unsubscribe from events and stop timers.

ComponentBase triggers renders for me. After an event handler it renders; if the handler is async and returns an incomplete Task, meaning it hit an await that did not finish synchronously, it renders once then and again when the task completes. Async lifecycle methods behave the same way, which is how a 'Loading…' state appears without any code from me. I call StateHasChanged myself only when something outside Blazor changed the state: a timer, a background task or an event from a singleton service. Then I call InvokeAsync(StateHasChanged) so it runs on the renderer's synchronisation context. The mistake I see is a child component that writes to its own [Parameter] property; the next time the parent re-renders, the value silently snaps back."


Ways to pass data

Mechanism Direction Use for
[Parameter] Parent β†’ child Inputs; treat as read-only
[Parameter, EditorRequired] Parent β†’ child Inputs the parent must supply (compiler warning)
RenderFragment ChildContent / RenderFragment<T> Parent β†’ child Templated markup, e.g. a row template
EventCallback<T> Child β†’ parent Events; parent re-renders automatically
@bind-Value + ValueChanged Two-way Input-style components
[CascadingParameter] Ancestor β†’ any descendant Auth state, theme, EditContext
Scoped service Any component in the scope Shared state with change notification

Lifecycle order

Method Runs Typical use
SetParametersAsync Every parameter set Rarely overridden; call base
OnInitialized{Async} Once per instance Load initial data
OnParametersSet{Async} After init and every new parameter set React to a changed route id
ShouldRender Before each re-render (not the first) Skip expensive renders
OnAfterRender{Async} After each render JS interop when firstRender
Dispose / DisposeAsync Removed from the tree Unsubscribe, stop timers

When a component re-renders

  • After its own event handler (an EventCallback also re-renders the parent).
  • When its parent re-renders and the parameters might have changed. Blazor can only prove no change for primitive and known immutable types; for complex objects it assumes a change and re-renders the child.
  • When StateHasChanged is called.

The reverse trap: if a parent mutates a list in place and the child decides with ShouldRender based on reference equality, the child never notices. Pick one rule (immutable data with new instances, or explicit change notification) and stick to it.

Production example

A dispatch screen showed 500 jobs, each a JobCard component taking a Job class parameter. A timer updated one clock every second, which re-rendered the parent and all 500 cards. Making the clock its own component, passing primitive parameters and adding @key dropped render time from about [180 ms] to [8 ms] per tick and stopped the circuit's CPU spikes.

πŸ” What the interviewer is checking

Checks that the candidate understands Blazor's data flow and render cycle well enough to avoid stale UI, double loads and leaks.

Green flags

  • States the lifecycle order and that OnInitialized runs once per instance
  • Knows when Blazor calls StateHasChanged automatically and why InvokeAsync is needed
  • Mentions @key and complex-parameter re-renders
  • Disposes subscriptions

Red flags

  • Mutates parameters inside the child
  • Calls JS interop from OnInitialized
  • Sprinkles StateHasChanged everywhere without knowing why

πŸ“š Learn in depth

1. Render tree and diffing

The Razor compiler turns markup into a BuildRenderTree(RenderTreeBuilder builder) method that emits frames: elements, attributes, text, child components. The renderer keeps the previous frames and computes a diff, which becomes a render batch.

Event (click) -> handler runs -> StateHasChanged queued
   -> BuildRenderTree() -> new frames
   -> diff with old frames -> render batch
   -> WebAssembly: apply to DOM directly
   -> Server: serialise batch -> SignalR -> blazor.web.js applies it

Because diffing is by position, a list that reorders can patch the wrong elements. @key tells the diff which item is which, keeping component instances and focus with the right row.

2. Single-threaded rendering

Each renderer has a synchronisation context: only one piece of component code runs at a time per circuit (Server) or on the browser main thread (WebAssembly). That is why code outside Blazor must call InvokeAsync(...). Calling StateHasChanged from a timer thread in Server mode throws "The current thread is not associated with the Dispatcher".

3. Async lifecycle and automatic renders

For OnInitializedAsync, Blazor renders once when the method yields at its first incomplete await (so you can show "Loading…") and again when the task completes. The same goes for async event handlers. If you have several awaits and want intermediate updates, call StateHasChanged() between them.

4. Parameter change detection

ParameterView is compared for each parameter. Strings, numbers, DateTime, Guid, decimal and similar are compared by value; anything else counts as possibly changed. This is why immutable records do not help on their own: Blazor still cannot prove they are unchanged. Use primitives, override ShouldRender, or split components.

5. Cascading values

<CascadingValue Value="theme"> makes a value available to descendants. Since .NET 8 you can register root-level cascading values in DI with AddCascadingValue, which also works across render-mode boundaries. Setting IsFixed="true" avoids subscription tracking when the value never changes, which matters on big trees.

6. Disposal and leaks

If a component subscribes to an event on a longer-lived service and never unsubscribes, the service keeps the component (and in Server mode the whole circuit) alive. Implement IDisposable and remove the handler.

Try it yourself

  1. Log every lifecycle method in a component and change a parameter from the parent; watch the order.
  2. Write a child that assigns its own [Parameter] and see it reset when the parent re-renders.
  3. Start a PeriodicTimer loop that calls StateHasChanged() directly in Server mode; read the exception, then fix it with InvokeAsync.
  4. Render 1,000 rows with and without @key, reorder them, and compare in the browser Performance tab.
  5. Override ShouldRender to return false after the first render and see which updates stop.

πŸ’» Code

A child raises an event; the parent (CartLine) binds to it with @bind-Value and re-renders when it fires. A timer shows when InvokeAsync(StateHasChanged) is needed.

@* QuantityPicker.razor (child) *@

<span>@Value</span>


@code {
    [Parameter, EditorRequired] public int Value { get; set; }
    [Parameter] public EventCallback

⚠ Common mistakes

  • Mistake: Assigning to a [Parameter] property inside the child. Why it is wrong: the parent overwrites it on its next render, so the change is lost. Instead: keep a private field or raise ValueChanged.
  • Mistake: Calling JS interop in OnInitializedAsync. Why it is wrong: the DOM does not exist yet and during prerendering there is no JS runtime. Instead: use OnAfterRenderAsync with firstRender.
  • Mistake: Calling StateHasChanged() from a timer or background thread. Why it is wrong: it is not on the renderer's dispatcher and throws in Server mode. Instead: await InvokeAsync(StateHasChanged).
  • Mistake: Calling StateHasChanged after every line "to be safe". Why it is wrong: it queues extra renders and hides the real data flow. Instead: rely on automatic renders and call it only for external changes.
  • Mistake: Loading data in OnInitializedAsync that depends on a route parameter. Why it is wrong: navigating from /orders/1 to /orders/2 reuses the instance and does not re-run init. Instead: load in OnParametersSetAsync when the id changes.
  • Mistake: Subscribing to a service event without unsubscribing. Why it is wrong: the service keeps the component and circuit alive, leaking memory. Instead: implement IDisposable and remove the handler.
  • Mistake: Rendering big lists without @key. Why it is wrong: reordering patches the wrong elements and loses focus or component state. Instead: @key="item.Id".

πŸ› Senior insight: trade-offs

Blazor's model is simple until a tree gets big. The senior skill is knowing why a component re-rendered: complex parameters force child re-renders, and in Server mode each render batch is network traffic and CPU on a shared server. I keep components small, pass primitives or ids where I can, isolate fast-changing parts into their own components and reach for ShouldRender only after measuring.

Technique When it fits Cost When not to
EventCallback up, parameters down Default for parent/child None Data needed ten levels down
Cascading value Cross-cutting context (auth, theme, form) Subscription tracking unless IsFixed Frequently changing app state
Scoped state service with OnChange event Siblings sharing state Must unsubscribe Two components that are parent and child
ShouldRender override Measured hot component Easy to cause stale UI Before profiling

I measure with the browser Performance tab for WebAssembly and with the .NET 10 Blazor metrics or dotnet-counters for Server.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions InvokeAsync and the renderer's dispatcher Why: Checks whether they connect Blazor's single-threaded rendering to SynchronizationContext and sync-over-async deadlocks
    How to answer

    A SynchronizationContext is an abstraction for "run this code in the right place", with Post (asynchronous) and Send (synchronous). WinForms, WPF, MAUI and Blazor install one so continuations return to the UI thread or renderer; legacy ASP.NET had one per request; ASP.NET Core and console apps have none. await captures the current context and posts the continuation to it. The classic deadlock: UI code calls .Result on an async method, blocking the only UI thread, while the method's continuation waits to be posted back to that same thread. Neither can proceed.

  2. When: Candidate compares Blazor parameters and EventCallback to React props and callbacks Why: Checks whether they can map Blazor concepts to the React model a full-stack team will also use
    How to answer

    React builds the UI from components: plain functions that take props (read-only inputs from the parent) and hold state (data the component owns, changed only through a setter from useState). When state changes, React re-renders that component, compares the new output with the old one and updates only the DOM nodes that changed, so the UI is always a function of state.

    Hooks add behaviour to function components: useState for state, useEffect to synchronise with things outside React such as a network call or a timer, and custom hooks to reuse that logic.

    A React app talks to an ASP.NET Core API with fetch (or a library like TanStack Query) returning JSON. React is only the client: validation, authorisation and data rules still live on the server. The trade-off is flexibility and a huge ecosystem against having to choose routing, data fetching and forms yourself.

↩ Usually asked after

More in Blazor

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me