Blazor Development Guidelines
You are an expert in Blazor development with deep knowledge of both Blazor Server and Blazor WebAssembly.
Component Architecture
Component Design
- Create small, focused components
- Use component parameters for input
- Use EventCallback for output/events
- Implement IDisposable for cleanup
- Use cascading parameters sparingly
Component Structure
Component Lifecycle
Lifecycle Methods
OnInitialized/OnInitializedAsync: Initial setupOnParametersSet/OnParametersSetAsync: When parameters changeOnAfterRender/OnAfterRenderAsync: After DOM updatesDispose: Cleanup resources
Best Practices
- Use
OnInitializedAsyncfor data loading - Check
firstRenderinOnAfterRenderAsync - Dispose subscriptions and timers
- Avoid long-running synchronous code
Data Binding
One-Way Binding
Two-Way Binding
Event Handling
Render Optimization
Prevent Unnecessary Renders
- Use
@keyfor list items - Implement
ShouldRender()when appropriate - Use
StateHasChanged()judiciously - Avoid inline handlers in loops
Virtualization
State Management
Component State
- Use private fields for component state
- Call
StateHasChanged()when state changes externally - Use
InvokeAsyncfor thread-safe updates
Cascading Parameters
State Containers
- Create injectable state services
- Use events for state change notifications
- Consider Fluxor for complex state management
Blazor Server vs WebAssembly
Blazor Server
- State lives on server
- Real-time connection via SignalR
- Faster initial load
- Requires stable connection
- Better for internal apps
Blazor WebAssembly
- Runs entirely in browser
- Larger initial download
- Works offline (PWA capable)
- No server resources per user
- Better for public apps
API Integration
HTTP Client
Error Handling
Error Handling
Error Boundaries
Global Error Handling
- Implement
IErrorBoundaryfor custom handling - Log errors to server
- Show user-friendly messages
Testing
bUnit Testing
Authentication
Setup
- Use
AuthenticationStateProvider - Use
AuthorizeViewfor conditional UI - Use
[Authorize]attribute on pages - Implement custom auth state provider for JWT
AuthorizeView
Performance Tips
- Use
@keyfor dynamic lists - Implement virtualization for large lists
- Lazy load components with
@if - Minimize JavaScript interop calls
- Use streaming rendering in .NET 8+


