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?
It's bad because:
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.