Skip to content

Adding StateHasChanged analyzer to flag unnecessary calls. - #67176

Merged
ilonatommy merged 9 commits into
dotnet:mainfrom
MayaKirova:mkirova/statehaschanged-analyzer
Jun 24, 2026
Merged

ilonatommy merged 9 commits into
dotnet:mainfrom
MayaKirova:mkirova/statehaschanged-analyzer

Conversation

@MayaKirova

Copy link
Copy Markdown
Contributor

Adding StateHasChanged analyzer to flag unnecessary calls.

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

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

Copilot AI review requested due to automatic review settings June 12, 2026 08:35
@MayaKirova
MayaKirova requested a review from a team as a code owner June 12, 2026 08:35
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Jun 12, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 StateHasChangedAnalyzer to report BL0012 for unnecessary StateHasChanged() calls.
  • Add StateHasChangedCodeFixProvider to 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

Comment on lines +222 to +224
<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 = @"
@javiercn javiercn added area-blazor Includes: Blazor, Razor Components analyzer Indicates an issue which is related to analyzer experience labels Jun 16, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.

Comment on lines +89 to +99
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();
Comment on lines +168 to +171
if (IsTargetLifecycleMethod(method.OverriddenMethod ?? method))
{
return true;
}
Comment on lines +183 to +189
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";
}
Comment on lines +115 to +127
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);
}
}
}
Comment on lines +222 to +224
<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>
Comment on lines +105 to +107
[Fact]
public void OnAsyncLifecycleEvents_WithStateHasChanged_ReportsDiagnostic()
{

@ilonatommy ilonatommy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

editor.RemoveNode(classDeclaration, SyntaxRemoveOptions.KeepExteriorTrivia);

and
.WithLeadingTrivia(invocationExpressionSyntax.GetLeadingTrivia())

so up to you, just make sure you're aware of its result.

@ilonatommy ilonatommy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job! 🚀

@MayaKirova

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree company="Infragistics, Inc"

@sbwalker

sbwalker commented Nov 6, 2026

Copy link
Copy Markdown

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

analyzer Indicates an issue which is related to analyzer experience area-blazor Includes: Blazor, Razor Components community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Blazor] StateHasChanged analyzer to flag unnecessary calls.

5 participants