In Blazor, why should a reusable data grid expose its sort request as an EventCallback<T> parameter rather than an Action<T>?
answer
- the receiver is the parent component
- parent re-renders after the handler
- awaits async handlers, then renders again
- an unset EventCallback is a safe no-op
- EventCallback.InvokeAsync returns Task
basics
~20 sAn EventCallback<T> remembers the component that created it, so invoking it runs the parent's handler and then re-renders the parent, including after an async handler completes. An Action<T> just calls the method, so the parent's UI stays stale until something else renders it.
solid answer
~40 sWhen a parent writes `<MaintenanceGrid OnSort="HandleSort" />` and `OnSort` is an `EventCallback<string>`, the Razor compiler builds the callback with the **parent as receiver**. The grid calls `await OnSort.InvokeAsync("NextServiceDue")`; Blazor routes that through the parent's `IHandleEvent.HandleEventAsync`, which runs `HandleSort`, calls `StateHasChanged` on the parent, and calls it again when a returned `Task` completes. With an `Action<string>` the grid would invoke the delegate directly: the parent's fields change but the parent does not re-render, and async handlers are not awaited. `EventCallback` also accepts sync or async handlers with or without the argument, is a struct whose unset value does nothing when invoked (`HasDelegate` tells you whether one was bound), and is treated as an immutable parameter type in change detection.
code
razor · 16 lines@* MaintenanceGrid.razor *@
@typeparam TItem
<th @onclick="() => RequestSort(nameof(WorkOrder.NextServiceDue))">Next service</th>
@code {
[Parameter] public EventCallback<string> OnSort { get; set; }
private async Task RequestSort(string column)
{
if (OnSort.HasDelegate)
{
await OnSort.InvokeAsync(column);
}
}
}go deeper
Know that child components raise events to their parent with an EventCallback parameter and call InvokeAsync on it.
Explain the receiver, why the parent re-renders automatically, how async handlers render twice, and why Action leaves the parent stale.
Use HasDelegate, method groups versus markup lambdas, and threading rules to keep callback-heavy components like grids predictable and cheap to re-render.
Standardise component event contracts across a component library - EventCallback types, naming, async expectations - so consuming teams never need defensive StateHasChanged calls.
## The problem: upward events in Blazor Data flows into a Blazor component through **parameters**; events flow back up through **callbacks** the parent passes in. In a fleet-maintenance app, a reusable `MaintenanceGrid<TItem>` shows work orders and lets the user click a column header to sort. The grid should not sort data it does not own; it should tell the page "sort by `NextServiceDue`" and let the page reload or reorder its list. The question is what type that callback parameter should have. ## How EventCallback works `EventCallback` and `EventCallback<TValue>` are `readonly struct` types in `Microsoft.AspNetCore.Components`. When the Razor compiler sees `<MaintenanceGrid OnSort="HandleSort" />` it creates the value through `EventCallback.Factory`, recording two things: - the **delegate** - `HandleSort`, which may be `Action`, `Action<string>`, `Func<Task>` or `Func<string, Task>`; - the **receiver** - the component that wrote the markup, here the page. When the grid calls `OnSort.InvokeAsync(column)`, Blazor hands the work to the receiver's `IHandleEvent.HandleEventAsync`. `ComponentBase` implements that by: 1. invoking the delegate; 2. calling `StateHasChanged()` on **the receiver** right away (unless `ShouldRender` says no); 3. if the delegate returned an unfinished `Task`, awaiting it and calling `StateHasChanged()` again. So the page re-renders with the new order, and an async handler that reloads data from an API renders twice - once at the start, once with the result - without the developer writing `StateHasChanged` anywhere. ## What goes wrong with Action<T> | Aspect | `EventCallback<T>` | `Action<T>` | |---|---|---| | Who re-renders | the parent that created it | nobody, beyond whatever the child's own event re-renders | | Async handler | awaited; parent renders again on completion | a `Func<T, Task>` would be needed and nothing awaits it for you | | Unset parameter | `InvokeAsync` returns a completed task | invoking `null` throws `NullReferenceException` | | Change detection | treated as immutable, so an unchanged method-group callback alone does not force the child to re-render | any delegate is an object type, so the child is always re-rendered with its parent | The symptom of using `Action<T>` is the classic "the handler ran, the data changed, but the parent page did not update until I clicked something else". Developers then sprinkle `StateHasChanged()` calls in the parent, which is exactly what `EventCallback` does for them. ## Practical rules - Prefer `EventCallback<T>` over the non-generic `EventCallback` when there is an argument: it is strongly typed, so the compiler checks handler signatures. - Name it like an event: `OnSort`, `OnRowSelected`; the `{Parameter}Changed` name is reserved for two-way binding. - Check `OnSort.HasDelegate` when the grid should behave differently if nobody listens (for example, hide the sort arrows). - Await `InvokeAsync` inside the child's own async handler so exceptions surface and ordering is predictable. - Do not store the callback and invoke it from a background thread; raise it from a UI event or marshal through `InvokeAsync` on the component.
- The grid's sort handler in the parent awaits an API call. How many times does the parent render, and why?Typically twice. `ComponentBase.HandleEventAsync` calls `StateHasChanged` right after invoking the handler, which shows any loading state set before the first await, and again when the returned `Task` completes, which shows the sorted data. If the handler completes synchronously there is only the first render.
- Can an EventCallback be passed to @bind:after?No. The data-binding docs state that an `EventCallback` or `EventCallback<T>` is not supported with `@bind:after`; pass a method returning `void` or `Task` instead. If the after-logic must reach the parent, call the parent's callback from inside that method.
- Action<T> and EventCallback<T> behave the same; EventCallback is only a naming convention.
- Invoking an EventCallback re-renders the child that invoked it, not the parent that supplied it.
- An EventCallback parameter that no parent set throws NullReferenceException when invoked.
- After an EventCallback handler the parent must always call StateHasChanged itself.
- EventCallback is a class, so null-check it before calling InvokeAsync.