Skip to content

Add a way to avoid component re-rendering caused by events to Blazor components ("pure event handlers") #18919

Closed
@Tragetaschen

Description

@Tragetaschen

Current status: #18919 (comment)

Is your feature request related to a problem? Please describe.

My Blazor component tree is connected to the business logic of the running application and represents its current state. There are a few event handlers (@onclick) and these directly call into the business logic to have an effect there. Any change of state in the business logic in turn is pushed to the Blazor components and cause them to rerender.

All the event handlers in the Blazor components are "pure" in the sense that they never change any state in the component. The current implementation of Blazor components though unconditionally re-renders (StateHasChanged) after the event callback has run even though this really isn't necessary for my components. A bit worse: The components are rendered with the old state after the event handler and then immediately the new state from the business logic arrives and causes a render for the new state.

Describe the solution you'd like

I pretty much look for a way to avoid this StateHasChanged call.

Currently I'm avoiding the rerender caused by this call by managing a shouldRender flag within my component and toggle it depending on what happens:

protected override void OnParametersSet() => shouldRender = true;

protected override bool ShouldRender()
{
    if (shouldRender)
    {
        shouldRender = false;
        return true;
    }
    else
        return false;
}

or

InvokeAsync(() =>
{
    shouldRender = true;
    StateHasChanged();
    shouldRender = false;
});

But this code is brittle, not very intuitive and hard to link to the reason why it's there, because I have to put it on the non-event side of things.

Metadata

Metadata

Assignees

Labels

DocsThis issue tracks updating documentationDoneThis issue has been fixedaffected-mostThis issue impacts most of the customersarea-blazorIncludes: Blazor, Razor Componentsfeature-blazor-component-modelAny feature that affects the component model for Blazor (Parameters, Rendering, Lifecycle, etc)feature-renderingFeatures dealing with how blazor renders componentsseverity-minorThis label is used by an internal tool

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions