blazorblazor-server-sideblazor-webassemblymudblazor

What's the point of using event callback in Blazor?


I was wondering if we call a function directly, why should we use event callback? For example, I use an event callback to set the colour of a component from the child to the parent.

This is the child component:

<button @onclick="OnButtonClick">Click me</button>

@code {

    [Parameter]
    public EventCallback<string> OnColorChange { get; set; }

    private async Task OnButtonClick()
    {
        await OnColorChange.InvokeAsync("new-color");
    }
}

This is parent component:

<ChildComponent OnColorChange="HandleColorChange" />  
    
@code {

    private string currentColorClass = "default-color";    

    private void HandleColorChange(string newColorClass)
    {
        currentColorClass = newColorClass;

    }
}

So, instead of the definition for HandleColorChange as a public static method, just call it directly, like this:

ParentComponent.HandleColorChange("new-color");

This isn't the only problem, we use JS interop to call C# functions, although we can handle all of these by calling them directly. The final question is, when should a method be called directly and when shouldn't it?


Solution

  • It's bad because:

    1. Components are meant to be reusable.
    2. You are tightly coupling the child to the parent.
    3. You can only have zero or one instances [which you can't guarantee]. Image a column component in a table: you would update all the columns.
    4. The various other reasons given by knowledgeable programmers in the comments.

    So:

    when we can handle by this way and when we shouldn't

    Never do it this way, which should be apparent from the comments.

    You're creating a single use component for a very specific use case. You might as well forget the component and just create a render fragment you can use in the parent component. That way you forgo all the expense of a component.

    In the end it's your code, so your decision.

    An important point to understand is you don't control the creation, lifecycle or disposal of components. That's the responsibility of the Renderer.