Skip to content

ListView with SelectedIndex bound to UseState enters re-render loop on first selection #495

Closed

Description

Summary

ListView with SelectedIndex bound to UseState enters a re-render storm after the first selection. A single user click causes dozens of renders and callback invocations before stabilizing. The final state is consistent (the user-selected index sticks), but the render thrash is severe.

Customer report:

"I take that back... I forgot to call setState. Once I do that, it goes into a CRAZY loop"

Minimal repro

public sealed class App : Component
{
    public override Element Render()
    {
        var (index, setIndex) = UseState(0);
        return ListView(new TextBlockElement[]
        {
            TextBlock("1"), TextBlock("2"), TextBlock("3"),
        }) with
        {
            SelectedIndex = index,
            OnSelectedIndexChanged = s => setIndex(s),
        };
    }
}

Standalone sample committed at samples/apps/listview-loop-repro/ for manual verification.

Programmatic confirmation

Selftest fixture ListViewLoop_StateBound_NoLoopAfterSelection (in tests/Reactor.AppTests.Host/SelfTest/Fixtures/ListViewLoopReproFixtures.cs) runs the same component pattern, programmatically sets lv.SelectedIndex = 1, then pumps render cycles and counts renders/callbacks:

TAP version 14
1..1
# Running: ListViewLoop_StateBound_NoLoopAfterSelection
ok ListViewLoop_Mounted
# ListViewLoop diag: renders+=23 callbacks+=47 lastIndex=1 finalControlIndex=1
not ok ListViewLoop_BoundedRenders - assertion failed
not ok ListViewLoop_BoundedCallbacks - assertion failed
ok ListViewLoop_FinalIndexIsUserSelection
ok ListViewLoop_StateMatchesControl

23 renders and 47 callback fires for a single programmatic selection change.

Root cause analysis

In src/Reactor/Core/V1Protocol/Handlers/ListViewHandler.cs:97-128, two distinct issues compound:

1. ItemsSource rebuild on every render (line 109-110)

if (!ReferenceEquals(o.Items, n.Items))
    lv.ItemsSource = Enumerable.Range(0, n.Items.Length).ToList();

The customer's ListView(new TextBlockElement[] { ... }) allocates a fresh array on every render. ReferenceEquals is always false, so ItemsSource is reassigned every Update. WinUI transiently resets SelectedIndex (often to -1) when ItemsSource is reassigned, and fires SelectionChanged for the transient value.

2. Unconditional SelectedIndex write with no echo suppression (line 126)

if (n.SelectedIndex >= 0) lv.SelectedIndex = n.SelectedIndex;

This bare write fires its own SelectionChanged event synchronously, and the handler's subscription has no ChangeEchoSuppressor gating. The synthetic echo reaches user code as if it were a real user selection.

Loop sequence

For a single lv.SelectedIndex = 1 from outside:

  1. WinUI fires SelectionChanged(1) → OnSelectedIndexChanged(1) → setIndex(1) → re-render queued.
  2. Render runs, returns element with new Items[] { ... } and SelectedIndex = 1.
  3. Update: line 109-110 rebuilds ItemsSource → WinUI internally drops to SelectedIndex = -1 → SelectionChanged(-1) fires → handler calls setIndex(-1) → state mutation queued.
  4. Update: line 126 writes lv.SelectedIndex = 1 → SelectionChanged(1) fires synchronously → handler calls setIndex(1) → state mutation queued.
  5. State commits, re-render runs with SelectedIndex = 1 again. Goto 3.

The loop terminates only because UseState's Equals short-circuit eventually catches a setIndex(sameValue) and the queue drains, but not before dozens of cycles.

Why this didn't show up earlier

  • SelectionEventFixtures.ListViewSelectionFires (tests/Reactor.AppTests.Host/SelfTest/Fixtures/SelectionEventFixtures.cs:84-113) does not bind SelectedIndex to state and uses a counter-only callback. No state mutation → no re-render → no Items reallocation → no loop.
  • The customer's original sample (also without state binding, just a (s) => { } no-op callback) didn't loop for the same reason. The loop is unique to the state-binding pattern, which is the recommended pattern.

Proposed fix

Two independent changes in ListViewHandler.Update, either of which alone would break the loop; both should be applied for correctness:

Fix 1 — only rebuild ItemsSource on actual length/content change

if (o.Items.Length != n.Items.Length)
    lv.ItemsSource = Enumerable.Range(0, n.Items.Length).ToList();

The current ReferenceEquals check makes the wrong assumption that callers will memoize their items array. The customer's new T[] { ... } literal is idiomatic Reactor and should not trigger a full container realization cycle.

Note that container content still has to re-mount on changes; that already happens via ContainerContentChanging reading the latest Items off the element tag (set on line 112). So we can safely skip the ItemsSource reassignment as long as the length is stable.

Fix 2 — echo-suppress the SelectedIndex write at line 126

if (n.SelectedIndex >= 0 && lv.SelectedIndex != n.SelectedIndex)
    ReactorBinding.WriteSuppressed(lv, () => lv.SelectedIndex = n.SelectedIndex);

Add the drift check (avoids no-op writes) and wrap in WriteSuppressed so the synthetic SelectionChanged is gated by ChangeEchoSuppressor.ShouldSuppress (which the handler at line 70-80 currently does NOT check — that's also a bug, but a smaller one once the write side is suppressed). Better still: also gate the handler at line 70 on ShouldSuppress for defense in depth.

Companion changes

  • Regression test: the fixture ListViewLoop_StateBound_NoLoopAfterSelection already added. Should pass with the proposed fixes.
  • Audit other hand-coded handlers: GridViewHandler, TemplatedListHandler, TemplatedTreeViewHandler may have the same ReferenceEquals(o.Items, n.Items) + unsuppressed SelectedIndex write pattern. Quick scan recommended.
  • Standalone repro app at samples/apps/listview-loop-repro/ for manual verification (kept as documentation; can be removed once fixed).

References

  • src/Reactor/Core/V1Protocol/Handlers/ListViewHandler.cs:97-128 — the offending Update method
  • src/Reactor/Core/V1Protocol/Handlers/ListViewHandler.cs:70-80 — unconditional SelectionChanged subscription with no echo suppression
  • tests/Reactor.AppTests.Host/SelfTest/Fixtures/ListViewLoopReproFixtures.cs — failing regression fixture
  • samples/apps/listview-loop-repro/App.cs — standalone repro
  • Related design discussion: .Controlled descriptor entries silently clobber user input on sibling re-renders when prop is not bound to state #494 (the broader .Controlled authority-model gap)

Activity

  1. added 2 commits that reference this issue on Jun 1, 2026
  2. added a commit that references this issue on Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions