Initializing State

Blazor.State adds several new lifecycle methods to your persistent components, aside from the normal Blazor lifecycle methods.

Lifecycle Methods

InitializeState

This method is called when the component's state is first initialized. This is the perfect place to initialize your component's state, as it is called only once during the component's lifecycle between the rendering environments. This method will be called when the component is initialized for the first time, and not when the component is re-rendered.

public class YourComponent : PersistentComponentBase
{
    [ComponentState]
    public int YourProperty { get; set; } = 0;

    protected override void InitializeState()
    {
        // Initialize your component's state here
        YourProperty = 420;
    }
}

InitializeStateAsync

This method works the same as InitializeState, but it is asynchronous. This is useful when you need to perform asynchronous operations to initialize your component's state. This method's invocation will be awaited before proceeding with initializing the component.

public class YourComponent : PersistentComponentBase
{
    [ComponentState]
    public int YourProperty { get; set; } = 0;

    protected override async Task InitializeStateAsync()
    {
        // Perform some asynchronous operation
        await Task.Delay(1000);

        YourProperty = 69;
    }
}