Skip to content

Blazor change detection fires for a property that does not change #11248

Closed
@Dotneteer

Description

@Dotneteer

Bug description:

In the following example (created from the default Blazor project), the Index component passes an input parameter, Initial, to Counter, and gets a notification whenever the counter value changes:

@page "/"

<Counter Initial="@Initial" Changed="@OnChanged"/>

@code 
{
int Initial = 7;

void OnChanged(CounterChangedArgs e)
{
    Console.WriteLine($"Value: {e.Value}, Initial: {Initial}");
}

Counter sets its starting value in the OnParametersSet lifecycle method. Whenever the counter's value changes, it sends a notification:

@page "/counter"

<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="@IncrementCount">Click me</button>

@code {
    int currentCount = 0;

    [Parameter]
    int Initial { get; set; }

    [Parameter]
    EventCallback<CounterChangedArgs> Changed {get; set; }

    protected override void OnParametersSet()
    {
        Console.WriteLine("OnParameterSet invoked.");
        currentCount = Initial;
    }

    async Task IncrementCount()
    {
        currentCount++;
        await Changed.InvokeAsync(new CounterChangedArgs(currentCount));
    }
}

Every time Counter raises the Changed event, Blazor invokes the OnParametersSet() method, though the single Initial input parameter of Counter does not change at all. If Changed is not raised or Index does not handle this event callback, everything works fine.

To Reproduce

Steps to reproduce the behavior:

  1. Compile and run the attached sample project: EventCallbackIssue.zip
  2. Use Developer Tools in browser to look at the console log. After three clicks it contains these messages:
WASM: OnParameterSet invoked.
WASM: Value: 8, Initial: 7
WASM: OnParameterSet invoked.
WASM: Value: 8, Initial: 7
WASM: OnParameterSet invoked.
WASM: Value: 8, Initial: 7
WASM: OnParameterSet invoked.

Expected behavior

I would expect this output (OnParametersSet invoked only once, as Initial does not change):
WASM: OnParameterSet invoked.
WASM: Value: 8, Initial: 7
WASM: Value: 9, Initial: 7
WASM: Value: 10, Initial: 7

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions