The way to destroy and re-create a component at runtime is to remove it from the RenderTree and the simplest way to do this is to use a @key directive that you willfully change.
Here is a basic ComponentReloader.razor that can be used either for @page components (by using it in MainLayout around the @Body)
<CascadingValue IsFixed=true Name=@Ident Value=ReloadChild> <div @key=childKey style="display:contents"> @ChildContent @if (ShowButton) { if (!ShowButtonInline) { <br /> } <button class="m-2 btn btn-danger" @onclick="ReloadChild">@ButtonTitle</button> } </div> </CascadingValue>
@code { [Parameter] public string Ident { get; set; } = "PageReload"; [Parameter] public required RenderFragment ChildContent { get; set; } = b => { }; [Parameter] public bool ShowButton { get; set; } = false; [Parameter] public bool ShowButtonInline { get; set; } = false; [Parameter] public string ButtonTitle { get; set; } = "Reload"; string childKey = Guid.NewGuid().ToString("d"); void ReloadChild() => InvokeAsync(() => { childKey = Guid.NewGuid().ToString("d"); StateHasChanged(); }); }
Of course, this is just a quick sample - you can adapt it as needed.
Note: style=display:contents ensures the div we are using to reload the component does not render on the page - just its contents get rendered.
Note: When the ReloadChild action is invoked (from its own button or called by the child component) it changes the childKey and re-renders - which causes Blazor to dispose (if applicable) of the components in its RenderTree and re-create them.
Example for MainLayout that renders a "Reload Page" button on every page:
<ComponentReloader Ident="ReloadPage" ShowButton=true ButtonTitle="Reload Page"> @Body </ComponentReloader>

Example for a counter component that wants to render its own button (or some other trigger):
<ComponentReloader Ident="ReloadCounter"><Counter/></ComponentReloader>
And in the counter you can get a reference to the ComponentReloader:
[CascadingParameter(Name = "ReloadCounter")] public Action? ComponentReload { get; set; }
Then it is just a matter of deciding how/when to call the ComponentReload action.
public void Reload() => ComponentReload?.Invoke();
@bind-Value/[value](just like normalinputbut web component doesn't get@bind=""support) and changing the value is a big pain with JS interop that I want to avoid, so getting a fresh component is much easier. AlsoDisposeis just an example to demonstrate a normal component's lifecycle, my current code does not actually use it.