Live Chat Icon For mobile
Live Chat Icon

How can I properly dispose a component in Blazor?

Platform: Blazor| Category: Components

Components should be disposed properly to avoid memory leak and allow proper garbage collection.  Managed resources used by the application will be disposed by the Blazor framework itself.

If a component implements IDisposable, the Dispose method will be called when the component is removed from the UI. You can use Dispose method to release unmanaged resources, unhook events, dispose DotNetObjectReference instances to avoid memory leak.

Refer to the following code sample.

@implements IDisposable
@inject IJSRuntime jsRuntime
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code { 
    DotNetObjectReference<HelloClass> dotNetObject { get; set; }
    protected override void OnInitialized()
        dotNetObject = DotNetObjectReference.Create<HelloClass>(new HelloClass());
    async Task IncrementCount()
        await jsRuntime.InvokeVoidAsync("MyJavaScriptFunction", new object[] { dotNetObject });
    void IDisposable.Dispose()
    public class HelloClass
        public void CustomMethod() { }

More information about component disposal can be found here.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.