blazor
  1. blazor-component-lifecycle

Blazor Component Lifecycle

Syntax

@code {...}

Example

@page "/counter"

<h1>Counter</h1>

<p>Current count: @_count</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int _count;

    private void IncrementCount()
    {
        _count++;
    }

    protected override void OnInitialized()
    {
        _count = 0;
    }
}

Output

Blazor Component Lifecycle Output

Explanation

Blazor component lifecycle methods are methods that are called at different stages during the lifecycle of a Blazor component. The lifecycle methods are executed in a specific order, which is as follows:

  1. OnInitialized() - Method is called once when the component is initialized.
  2. OnParametersSet() - Method is called each time the component parameters are updated.
  3. OnAfterRender() - Method is called after the component has been rendered.
  4. OnDispose() - Method is called when the component is disposed.

Use

Blazor component lifecycle methods can be used to perform specific tasks during different stages of the component lifecycle. For example, the OnInitialized() method can be used to perform initialization tasks such as initializing variables, setting up event handlers, or fetching data from a database.

Important Points

  • Blazor component lifecycle methods are executed in a specific order.
  • The OnInitialized() method is called once when the component is initialized.
  • The OnParametersSet() method is called each time the component parameters are updated.
  • The OnAfterRender() method is called after the component has been rendered.
  • The OnDispose() method is called when the component is disposed.

Summary

Blazor component lifecycle methods are a powerful feature that can be used to perform specific tasks during different stages of the component lifecycle. Knowing the execution order of the different lifecycle methods is crucial for writing well-structured and maintainable Blazor components.

Published on: