blazor
  1. blazor-component-state

Blazor Component State

Blazor components are structured as classes, which have their own state that can determine how they behave and what they display. The component's state can be manipulated by the component itself or by parent components.

Syntax

public class CounterComponent : ComponentBase
{
    private int currentCount = 0;
    
    // ...
}

In this example, a CounterComponent class is defined as a subclass of ComponentBase. The class has a private field currentCount, which will be used to store the current count state of the component.

Example

@page "/counter"

<h1>Counter</h1>

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

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

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

In this example, a simple counter component is defined. It has a currentCount field which is initially set to zero, and a button that triggers the IncrementCount method when clicked. The method increases the count by one, updating the component's state.

Output

The output of the above example will be a simple web page with a title of "Counter", the current count displayed on the page, and a button that allows the user to increment the count:

Blazor component state example output

Explanation

Blazor components are structured as classes, which have their own state that can determine how they behave and what they display. The component's state can be manipulated by the component itself or by parent components.

In the example above, a CounterComponent class is defined which has a private currentCount field that stores the current count state of the component. Clicking on the button calls the IncrementCount method, which increments the count by one and updates the state of the component.

Use

Blazor component state is used to keep track of the state of a component and to determine how it behaves and what it displays. Components can have a large number of states, which can be used to create dynamic and reactive user interfaces.

Important Points

  • Blazor components have their own state that can be used to determine their behavior and what they display.
  • The component's state can be manipulated by the component itself or by parent components.
  • State should be updated using the StateHasChanged method to trigger UI rendering.
  • Care should be taken when using state to avoid creating side-effects or inconsistent state.

Summary

Blazor component state is a critical part of Blazor development, allowing developers to create dynamic and reactive user interfaces. By manipulating a component's state, developers can control how the component behaves and what it displays. Care should be taken when using state to avoid creating side-effects or inconsistent state.

Published on: