blazor
Mindrally/skills/blazor/SKILL.md
Guidelines for Blazor development including component lifecycle, state management, and performance optimization
Skill258 starsChanged 8 months ago
What's in it
- Blazor Development Guidelines
- Component Architecture
- Component Design
- Component Structure
- Component Lifecycle
- Lifecycle Methods
- Best Practices
- Data Binding
- One-Way Binding
- Two-Way Binding
- Event Handling
- Render Optimization
- Prevent Unnecessary Renders
- Virtualization
- State Management
- Component State
- Cascading Parameters
- State Containers
- Blazor Server vs WebAssembly
- Blazor Server
- Blazor WebAssembly
- API Integration
- HTTP Client
- Error Handling
- Error Handling
- Error Boundaries
- Global Error Handling
- Testing
- bUnit Testing
- Authentication
---
name: blazor
description: Guidelines for Blazor development including component lifecycle, state management, and performance optimization
---
# 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
```razor
@page "/users/{Id:int}"
@inject IUserService UserService
<h1>@User?.Name</h1>
@code {
[Parameter]
public int Id { get; set; }
private User? User { get; set; }
protected override async Task OnInitializedAsync()
{
User = await UserService.GetUserAsync(Id);
}
}
```
## Component Lifecycle
### Lifecycle Methods
- `OnInitialized`/`OnInitializedAsync`: Initial setup
- `OnParametersSet`/`OnParametersSetAsync`: When parameters change
- `OnAfterRender`/`OnAfterRenderAsync`: After DOM updates
- `Dispose`: Cleanup resources
### Best Practices
- Use `OnInitializedAsync` for data loading
- Check `firstRender` in `OnAfterRenderAsync`
- Dispose subscriptions and timers
- Avoid long-running synchronous code
## Data Binding
### One-Way Binding
```razor
<p>@message</p>
<input value="@inputValue" />
```
### Two-Way Binding
```razor
<input @bind="inputValue" />
<input @bind="inputValue" @bind:event="oninput" />
```
### Event Handling
```razor
<button @onclick="HandleClick">Click</button>
<button @onclick="() => HandleClickWithParam(id)">Click</button>
<button @onclick="HandleClickAsync">Async Click</button>
```
## Render Optimization
### Prevent Unnecessary Renders
- Use `@key` for list items
- Implement `ShouldRender()` when appropriate
- Use `StateHasChanged()` judiciously
- Avoid inline handlers in loops
### Virtualization
```razor
<Virtualize Items="@items" Context="item">
<ItemContent>
<div>@item.Name</div>
</ItemContent>
</Virtualize>
```
## State Management
### Component State
- Use private fields for component state
- Call `StateHasChanged()` when state changes externally
- Use `InvokeAsync` for thread-safe updates
### Cascading Parameters
```razor
<CascadingValue Value="@currentTheme">
<ChildComponent />
</CascadingValue>
<!-- In child component -->
[CascadingParameter]
public Theme CurrentTheme { get; set; }
```
### 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
```csharp
@inject HttpClient Http
private async Task LoadData()
{
users = await Http.GetFromJsonAsync<List<User>>("api/users");
}
```
### Error Handling
```csharp
try
{
users = await Http.GetFromJsonAsync<List<User>>("api/users");
}
catch (HttpRequestException ex)
{
errorMessage = "Failed to load users";
}
```
## Error Handling
### Error Boundaries
```razor
<ErrorBoundary>
<ChildContent>
<RiskyComponent />
</ChildContent>
<ErrorContent Context="ex">
<p>An error occurred: @ex.Message</p>
</ErrorContent>
</ErrorBoundary>
```
### Global Error Handling
- Implement `IErrorBoundary` for custom handling
- Log errors to server
- Show user-friendly messages
## Testing
### bUnit Testing
```csharp
[Fact]
public void ComponentRendersCorrectly()
{
using var ctx = new TestContext();
var cut = ctx.RenderComponent<Counter>();
cut.Find("p").MarkupMatches("<p>Current count: 0</p>");
cut.Find("button").Click();
cut.Find("p").MarkupMatches("<p>Current count: 1</p>");
}
```
## Authentication
### Setup
- Use `AuthenticationStateProvider`
- Use `AuthorizeView` for conditional UI
- Use `[Authorize]` attribute on pages
- Implement custom auth state provider for JWT
### AuthorizeView
```razor
<AuthorizeView>
<Authorized>
<p>Welcome, @context.User.Identity?.Name!</p>
</Authorized>
<NotAuthorized>
<p>Please log in.</p>
</NotAuthorized>
</AuthorizeView>
```
## Performance Tips
- Use `@key` for dynamic lists
- Implement virtualization for large lists
- Lazy load components with `@if`
- Minimize JavaScript interop calls
- Use streaming rendering in .NET 8+
More agent context in Mindrally/skills
264 other files this repository gives its agents, the first 60 shown.
Skill
- accessibility-a11yaccessibility-a11y/SKILL.md
- alpine-jsalpine-js/SKILL.md
- analytics-data-analysisanalytics-data-analysis/SKILL.md
- android-developmentandroid-development/SKILL.md
- angular-developmentangular-development/SKILL.md
- angularangular/SKILL.md
- anime-jsanime-js/SKILL.md
- anthropic-claude-developmentanthropic-claude-development/SKILL.md
- api-developmentapi-development/SKILL.md
- apollo-graphqlapollo-graphql/SKILL.md
- aspnet-coreaspnet-core/SKILL.md
- astroastro/SKILL.md
- auth0-authenticationauth0-authentication/SKILL.md
- autogen-developmentautogen-development/SKILL.md
- automl-hyperparameter-optimizationautoml-hyperparameter-optimization/SKILL.md
- aws-developmentaws-development/SKILL.md
- azureazure/SKILL.md
- backend-developmentbackend-development/SKILL.md
- bash-scriptingbash-scripting/SKILL.md
- beautifulsoup-parsingbeautifulsoup-parsing/SKILL.md
- bitbucket-workflowbitbucket-workflow/SKILL.md
- blender-python-addonblender-python-addon/SKILL.md
- blockchainblockchain/SKILL.md
- bootstrapbootstrap/SKILL.md
- business-central-developmentbusiness-central-development/SKILL.md
- cheerio-parsingcheerio-parsing/SKILL.md
- chrome-extension-developmentchrome-extension-development/SKILL.md
- ci-cd-best-practicesci-cd-best-practices/SKILL.md
- clean-architectureclean-architecture/SKILL.md
- clean-codeclean-code/SKILL.md
- clerk-authenticationclerk-authentication/SKILL.md
- cloudflare-developmentcloudflare-development/SKILL.md
- computer-vision-opencvcomputer-vision-opencv/SKILL.md
- convexconvex/SKILL.md
- cppcpp/SKILL.md
- c-sharpc-sharp/SKILL.md
- csscss/SKILL.md
- cypresscypress/SKILL.md
- data-analysis-jupyterdata-analysis-jupyter/SKILL.md
- data-analystdata-analyst/SKILL.md
- data-jupyter-pythondata-jupyter-python/SKILL.md
- deep-learning-pythondeep-learning-python/SKILL.md
- deep-learning-pytorchdeep-learning-pytorch/SKILL.md
- deep-learningdeep-learning/SKILL.md
- deno-typescriptdeno-typescript/SKILL.md
- design-systemsdesign-systems/SKILL.md
- devopsdevops/SKILL.md
- django-pythondjango-python/SKILL.md
- django-rest-api-developmentdjango-rest-api-development/SKILL.md
- dockerdocker/SKILL.md
- dotnetdotnet/SKILL.md
- drizzle-ormdrizzle-orm/SKILL.md
- drupal-developmentdrupal-development/SKILL.md
- elasticsearch-best-practiceselasticsearch-best-practices/SKILL.md
- electron-developmentelectron-development/SKILL.md
- elixirelixir/SKILL.md
- embedded-stm32embedded-stm32/SKILL.md
- esbuild-bundleresbuild-bundler/SKILL.md
- ethereumethereum/SKILL.md
- expo-react-native-javascript-best-practicesexpo-react-native-javascript-best-practices/SKILL.md
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
Reports can't be read right now.
Posts are public. Sign in to say whether it worked for you.Sign in to post
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

