Search code examples
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 call back ? for example i use event callback to set color of a component from child to parent

this is 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");
    }
}

and this is parent component

<ChildComponent OnColorChange="HandleColorChange" />



@code {
    private string currentColorClass = "default-color";


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

    }
}

so insted of all of these define HandleColorChange as public static and we can just call it directly like this

ParentComponent.HandleColorChange("new-color");

and this isn't only problem , we use js interop to call c# function , although we can handle all of these by calling it directly, and the final question is : when we can handle by this way and when we shouldn't


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.