Getting Started

Installation

Add this nuget package to both your Server and Client Blazor application projects:

dotnet add package BitzArt.Blazor.State

Configuration

Call this method in both your Server Program.cs and Client Program.cs and reference all assemblies in your project that may contain persistent components:

⚠️ Manually registering assemblies is a temporary step until a better solution is implemented. We expect this step to go away in one of the future releases.

builder.Services.AddBlazorState(state =>
{
    state.AddAssembly(someAssembly); // Registers a specified assembly
    state.AddAssemblyContaining<Program>(); // Registers an assembly where the referenced class is declared
});

ℹ️ You can find more information on registering assemblies in the source code

Use Blazor.State

To persist your components' state across rendering environments, follow these steps:

1. Inherit from PersistentComponentBase

Make sure your persistent components inherit from the PersistentComponentBase base class.

@inherits PersistentComponentBase // in your .razor file

or

public class YourComponent: PersistentComponentBase // in your .cs file

2. Mark state properties with [ComponentState] attribute

Use ComponentStateAttribute to mark properties that need to be persisted across rendering environments

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

3. Make sure the page is stateful

Any page containing persistent components, must also be stateful. This is a requirement due to how Blazor.State is implemented under the hood. This can be achieved by making sure your page component inherits from PersistentComponentBase, similarly to how any persistent component would.

4. Make sure your page meets the state hierarchy requirements

To learn more about page state hierarchy, refer to the State Hierarchy section.

5. Include the necessary JS code

⚠️ This is a temporary step until a better solution is implemented. We expect this step to go away in one of the future releases.

Include this JS file in your Client project's wwwroot folder.

Then, also include the following line in your App.razor:

<script src="app.js"></script>

6. Enjoy

That's it! Your components' state should now be persisted across rendering environments.

You can learn more about initializing your components' state in the Initializing State section.