Repository navigation
Adding StateHasChanged analyzer to flag unnecessary calls. - #67176
Conversation
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds a new Roslyn analyzer + code fix to detect and remove redundant StateHasChanged() calls in Blazor component lifecycle methods and event handlers, along with supporting diagnostics/resources and tests.
Changes:
- Introduce
StateHasChangedAnalyzerto reportBL0012for unnecessaryStateHasChanged()calls. - Add
StateHasChangedCodeFixProviderto remove the reported call sites. - Add new tests plus diagnostic descriptor and localized resources for the new rule.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Components/Analyzers/src/StateHasChangedAnalyzer.cs | Implements BL0012 analyzer logic for lifecycle methods and EventCallback handlers |
| src/Components/Analyzers/src/StateHasChangedCodeFixProvider.cs | Adds a code fix to remove flagged invocations |
| src/Components/Analyzers/src/DiagnosticDescriptors.cs | Registers the new BL0012 diagnostic descriptor |
| src/Components/Analyzers/src/Resources.resx | Adds title/message/description/fix-title resources for BL0012 |
| src/Components/Analyzers/test/StateHasChangedAnalyzerTest.cs | Adds analyzer diagnostics tests |
| src/Components/Analyzers/test/StateHasChangedCodeFixProviderTest.cs | Adds code-fix behavior tests |
| <data name="UnnecessaryStateHasChangedCall_Description" xml:space="preserve"> | ||
| <value>StateHasChanged is unnecessary immediately after the first await and after the final await in component lifecycle methods or event handlers because ComponentBase already schedules renders at those points.</value> | ||
| </data> |
|
|
||
| public class StateHasChangedCodeFixProviderTest : CodeFixVerifier | ||
| { | ||
| private static readonly string ComponentDeclarations = @" |
| var body = methodDeclaration.Body; | ||
| if (body is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var awaitExpressions = body.DescendantNodes(static node => !IsNestedFunctionLike(node)).OfType<AwaitExpressionSyntax>().OrderBy(n => n.SpanStart).ToList(); | ||
| var stateCalls = body.DescendantNodes(static node => !IsNestedFunctionLike(node)).OfType<InvocationExpressionSyntax>() | ||
| .Where(invocation => IsStateHasChangedCall(syntaxContext.SemanticModel, invocation)) | ||
| .OrderBy(invocation => invocation.SpanStart) | ||
| .ToList(); |
| if (IsTargetLifecycleMethod(method.OverriddenMethod ?? method)) | ||
| { | ||
| return true; | ||
| } |
| private static bool IsStateHasChangedCall(SemanticModel semanticModel, InvocationExpressionSyntax invocation) | ||
| { | ||
| return semanticModel.GetSymbolInfo(invocation).Symbol is IMethodSymbol method && | ||
| method.MethodKind == MethodKind.Ordinary && | ||
| method.Parameters.Length == 0 && | ||
| method.Name == "StateHasChanged"; | ||
| } |
| else | ||
| { | ||
| var firstAwaitStart = awaitExpressions[0].SpanStart; | ||
| var lastAwaitStart = awaitExpressions[awaitExpressions.Count - 1].SpanStart; | ||
| foreach (var stateCall in stateCalls) | ||
| { | ||
| if (stateCall.SpanStart < firstAwaitStart || stateCall.SpanStart > lastAwaitStart) | ||
| { | ||
| // any calls before the first await or after the last one are redundant, because ComponentBase calls StateHasChanged afterwards. | ||
| AddCallLocation(callLocations, stateCall); | ||
| } | ||
| } | ||
| } |
| <data name="UnnecessaryStateHasChangedCall_Description" xml:space="preserve"> | ||
| <value>StateHasChanged is unnecessary immediately before the first await and after the final await in component lifecycle methods or event handlers because ComponentBase already schedules renders at those points.</value> | ||
| </data> |
| [Fact] | ||
| public void OnAsyncLifecycleEvents_WithStateHasChanged_ReportsDiagnostic() | ||
| { |
ilonatommy
left a comment
There was a problem hiding this comment.
Good job!
I made a short analysis of 'StateHasChanged' calls in the framework's lifecycle methods to make sure we are covering
everything. These that automatically call 'StateHasChanged' on behalf of user-overridable methods are:
| # | File | Line | Context / Reason |
|---|---|---|---|
| 1 | ComponentBase.cs | 288 | After sync part of OnInitializedAsync completes (before awaiting the task) |
| 2 | ComponentBase.cs | 327 | In CallOnParametersSetAsync — triggers re-render after OnParametersSet and sync part of OnParametersSetAsync |
| 3 | ComponentBase.cs | 352 | In CallStateHasChangedOnAsyncCompletion — after an async lifecycle method finishes |
| 4 | ComponentBase.cs | 364 | In IHandleEvent.HandleEventAsync — automatically re-renders after every event callback |
It is generally good to have similar context included in the description of the PR to indicate what you took into consideration when implementing the fix.
Beyond the small comments I added in the code, it would be good to make sure we have full test coverage. I made a table with what we have and what could be added:
| # | Scenario | Kind | Status |
|---|---|---|---|
| True positives (should flag) | |||
| 1 | StateHasChanged in sync OnInitialized |
TP | ✅ Covered |
| 2 | StateHasChanged in sync OnParametersSet |
TP | ✅ Covered |
| 3 | StateHasChanged before first await in OnInitializedAsync |
TP | ✅ Covered |
| 4 | StateHasChanged after last await in OnInitializedAsync |
TP | ✅ Covered |
| 5 | StateHasChanged before first await in OnParametersSetAsync |
TP | ✅ Covered |
| 6 | StateHasChanged after last await in OnParametersSetAsync |
TP | ✅ Covered |
| 7 | StateHasChanged before first/after last await in async event handler (Func<Task>) |
TP | ✅ Covered |
| 8 | StateHasChanged in sync event handler (Action, no awaits) |
TP | ❌ Missing |
| 9 | StateHasChanged in single-await lifecycle method | TP | ❌ Missing |
| 10 | StateHasChanged in single-await event handler | TP | ❌ Missing |
| 11 | Expression-bodied => StateHasChanged() |
TP | ❌ Missing |
| 12 | Multi-level inheritance (MyComponent : MyBase : ComponentBase) |
TP | ❌ Missing |
| 13 | this.StateHasChanged() explicit qualifier |
TP | ❌ Missing |
| 14 | Sync event handler with Action<T> (parameterized) |
TP | ❌ Missing |
| False positives (should NOT flag) | |||
| 15 | StateHasChanged between two awaits | FP | ❌ Missing |
| 16 | Non-ComponentBase class with OnInitialized method |
FP | ❌ Missing |
| 17 | StateHasChanged inside a lambda/local function | FP | ❌ Missing |
| 18 | StateHasChanged in InvokeAsync(() => StateHasChanged()) |
FP | ❌ Missing |
| 19 | Private method that's NOT an event handler | FP | ❌ Missing |
| 20 | StateHasChanged in SetParametersAsync |
FP | ❌ Missing |
| Code fix tests | |||
| 21 | Remove StateHasChanged in sync OnInitialized |
Fix | ✅ Covered |
| 22 | Remove only boundary StateHasChanged, keep middle | Fix | ✅ Covered |
| 23 | Remove StateHasChanged in sync event handler | Fix | ❌ Missing |
| 24 | Remove StateHasChanged in expression-bodied method | Fix | ❌ Missing |
| 25 | Fix preserves StateHasChanged between awaits when removing redundant occurrences | Fix | ❌ Missing |
| ? (SyntaxNode)expressionStatement | ||
| : invocation; | ||
|
|
||
| var newRoot = root.RemoveNode(nodeToRemove, SyntaxRemoveOptions.KeepExteriorTrivia); |
There was a problem hiding this comment.
KeepExteriorTrivia is leaving blank whitespaces in the place where StateHasChanged() was. There's also KeepLeadingTrivia that would clean up the whitespace. Not sure what is better, I would prefer no whitespace but I can see
and
so up to you, just make sure you're aware of its result.
…oid OnInitialized() => StateHasChanged();
|
@dotnet-policy-service agree company="Infragistics, Inc" |
|
Does this analyzer handle scenarios where the render mode is determined dynamically at run-time? I am the maintainer of the Oqtane Framework (https://github.com/oqtane/oqtane.framework) and it allows the Render Mode (static/interactive) and Interactivity (Server/WebAssembly) to be specified at run-time... and depending on the run-time configuration, some components may need to utilize StateHasChanged to refresh data. In .NET 11 the analyzer seems to be doing static analysis and making assumptions about the run-time configuration - so it is producing invalid compilation warnings (ie. if we removed the identified StateHasChanged calls it would actually break the functionality of our application depending on the run-time configuration). I am not sure if this scenario was considered when the enhancement was added. @danroth27 I suppose the solution is to disable the BL0012 warning in our solution since it seems to produce false positives. |
Adding StateHasChanged analyzer to flag unnecessary calls.
Description
Added an analyzer that warns of unnecessary StateHasChanged usages as described #65196.
Not sure if a code fix is necessary or not, but I added one anyway.
First try at contributing here. Hopefully I got all the scenarios right.
Fixes #65196