State in Blazor:
In Blazor, the user’s state is held in the server’s memory in a circuit. State Management refers to the persisting state of an application even after the connection is lost or disconnected. The state held for a user’s circuit may be any of the following,
- UI related data- component instances, rendered
output
- Property/field values of the component instances
- Dependency injection service instance data
Need for State Management:
In Blazor, the
application is connected through a circuit to the server, which holds the user’s state and this
can be lost or disconnected due to multiple reasons. Some of the reasons are as
follows,
- Large number of users accessing the server and
increasing the memory used causing the pressure to disconnect the circuit.
- Users reloading the application/webpage leading
to circuit disconnection/loss.
Due to the above,
user’s state may be lost and can also cause loss of crucial data gathered in
the application such as,
- Multistep webform
- Shopping cart
When data is
lost after completing processes with multiple steps or creating a shopping list,
it results in unnecessary time consumption. So, in Blazor, the data is stored in the local
cache and state persists even when the circuit gets disconnected.
Persisting the State/State Management:
The three
locations for persisting state in a Blazor application are as follows,
- Server-side (Database)
- Client-side (Browser)
- URL
Server-side (Database):
To store data/state permanently or any data
that spans multiple users or devices, the server-side database should be used.
Client-side (Browser):
Most suited when the user is actively creating transient data, that can be stored in the browsers, localStorage and sessionStorage.
URL:
This is best suited when the data/state
needs to persist when navigating from one page of the application to another.
For more information on state management, refer here.
View Sample in GitHub
Permalink