[Due for payment 2026-11-23] [$250] [Sentry: APP-JVF] Web: useSidebarOrderedReports setState loop, "Maximum update depth exceeded"
Sentry
https://expensify.sentry.io/issues/APP-JVF
Impact (snapshot at filing)
- Users (total since first seen): 68
- Events: 110
- Users (last 14d, all versions): 20
- Users (last 14d, production 9.5.11 to 9.5.13): 3 (25 events)
- First seen: 2026-08-05 (about 2.5 months ago)
- Last seen: 2026-10-19 (ongoing)
- Platform: web (standalone)
- App version(s): 9.5.0 to 9.5.13. Most users are on 9.5.6 and 9.5.5.
- Affected route(s) (parameterized): mostly
/search, also/search/r/:reportID - Mechanism: generic, level fatal,
app_blocking: true
Stack trace (top frames, first-party only)
src/hooks/useSidebarOrderedReports.tsx:328 useEffect -> setCurrentReportsToDisplay(reportsToDisplayInLHN)
react-dom commitHookEffectListMount -> dispatchSetState -> getRootForUpdatedFiber
Error: Maximum update depth exceeded (React #185)
Suspected cause
The effect at useSidebarOrderedReports.tsx:328 copies reportsToDisplayInLHN into state each time the memo returns a new object. The memo at line 229 leaves currentReportsToDisplay out of its dependencies on purpose, to avoid a loop. So a loop here means that one of the memo's other dependencies gets a new identity on every render on /search.
Reproduction
Unknown. See the Sentry events linked from the Sentry issue.
Related
- Sibling Sentry IDs: none confirmed
- Prior GH issues: none found
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022112637803657814041
- Upwork Job ID: 2112637803657814041
- Last Price Increase: 2026-11-06
Issue Owner
Current Issue Owner: @mallenexpensify
Triggered auto assignment to Contributor-plus team member for initial proposal review - @parasharrajat (External)
Job added to Upwork: https://www.upwork.com/jobs/~022112637803657814041
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0170d6b02e9440e604
Proposal
Please re-state the problem that we are trying to solve in this issue.
Sentry issue APP-JVF: On Web (primarily on /search and /search/r/:reportID), a fatal Maximum update depth exceeded React error occurs due to an infinite setState re-render loop in useSidebarOrderedReports.tsx:328.
What is the root cause of that problem?
In src/hooks/useSidebarOrderedReports.tsx:327-329:
useEffect(() => {
setCurrentReportsToDisplay(reportsToDisplayInLHN);
}, [reportsToDisplayInLHN]);
reportsToDisplayInLHNis computed by auseMemoat line 229. WhilecurrentReportsToDisplayis intentionally excluded from theuseMemodependency array to prevent simple dependency loops,reportsToDisplayInLHNreadscurrentReportsToDisplayduring computation (e.g.hasCachedReports = Object.keys(currentReportsToDisplay).length > 0).- When on
/searchroutes or whencurrentReportId/ related collection keys trigger re-evaluation:- If
shouldDoIncrementalUpdateis false (such as initial build, cache eviction, or whengetReportsToDisplayInLHNexecutes from scratch),SidebarUtils.getReportsToDisplayInLHNallocates a newreportsToDisplayobject dictionary (const reportsToDisplay: ReportsToDisplayInLHN = {}). - Even when
shouldDoIncrementalUpdateis true, if any dynamic report property (requiresAttention,hasErrorsOtherThanFailedReceipt, orisUnreadReport) differs from the previous reference or creates a modified entry,getMutableCopy()produces a new object reference. - Crucially, in
useSidebarOrderedReports.tsx:327-329,setCurrentReportsToDisplay(reportsToDisplayInLHN)is called unconditionally on every reference change ofreportsToDisplayInLHN.
- If
- If an upstream trigger (such as route change or unmemoized collection selector) causes
useMemoto return a new object with identical content, or ifSidebarUtils.getReportsToDisplayInLHNgenerates a new object identity each render,setCurrentReportsToDisplaytriggers a re-render. On subsequent render, ifgetReportsToDisplayInLHNrebuilds from scratch, a new object reference is returned again, triggeringsetCurrentReportsToDisplayin a continuous cascading loop until React aborts withMaximum update depth exceeded.
What changes do you think we should make in order to solve the problem?
-
Guard
setCurrentReportsToDisplaywith shallow dictionary equality inuseSidebarOrderedReports.tsx: Insrc/hooks/useSidebarOrderedReports.tsx:327-329: ImportshallowComparefrom@libs/ObjectUtils:useEffect(() => { setCurrentReportsToDisplay((prev) => { if (shallowCompare(prev, reportsToDisplayInLHN)) { return prev; } return reportsToDisplayInLHN; }); }, [reportsToDisplayInLHN]);- Why this is optimal:
shallowComparechecks whetherprevandreportsToDisplayInLHNshare identical keys and report reference values. IfreportsToDisplayInLHNreturned a new object dictionary but its report entries have not actually changed, returningprevcauses React to bail out of state updates completely, terminating the infinite loop immediately.
- Why this is optimal:
-
Add referential stability to
SidebarUtils.getReportsToDisplayInLHN: Insrc/libs/SidebarUtils.ts:358-359: Before returningreportsToDisplay, compare againstlastReportsToDisplayInLHN:if (lastReportsToDisplayInLHN && shallowCompare(lastReportsToDisplayInLHN, reportsToDisplay)) { return lastReportsToDisplayInLHN; } lastReportsToDisplayInLHN = reportsToDisplay; return reportsToDisplay;This ensures that
getReportsToDisplayInLHNpreserves referential stability across successive renders when report contents remain identical.
What specific scenarios should we cover in automated tests?
In tests/unit/useSidebarOrderedReportsTest.tsx:
- Assert that when
reportsToDisplayInLHNis recomputed with identical reports (new dictionary reference with identical key/value entries),currentReportsToDisplaydoes not trigger additional component re-renders. - Assert that navigating to
/searchor changingcurrentReportIdto an unlisted search report does not trigger circularsetCurrentReportsToDisplayloops.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
On web, mostly on /search, the app crashes with Maximum update depth exceeded from the effect in useSidebarOrderedReports that copies reportsToDisplayInLHN into state.
What is the root cause of that problem?
The LHN cache never settles when at least one displayed report has a flag (unread, requires attention, or errors). Every recompute of reportsToDisplayInLHN returns a new object, so the effect sets new state on every pass.
updateReportsToDisplayInLHN is meant to keep the same object when nothing changed (it has a lazy copy for that, SidebarUtils.ts#L401). But for a flagged report it stores a copy, {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport} (L456), and on the next pass it checks existingEntry !== report (L451). The stored entry is the copy, never the report itself, so that check is always true. Each call makes a new entry and a new map even with identical input.
I confirmed this two ways:
- Unit test: calling
updateReportsToDisplayInLHNtwice with the same inputs and one report that hasrequiresAttention: truereturns a different object and a different entry the second time. - In the app (local web, latest main, one unread chat in the LHN), with a temporary log in the effect at L328. Toggling Account > Troubleshoot > Force offline on and off changes no report, but:
BEFORE (main)
cache write #1 | newObject=true | entries=2 | entriesReallyChanged=0
cache write #2 | newObject=true | entries=2 | entriesReallyChanged=0
cache write #3 | newObject=true | entries=2 | entriesReallyChanged=0
cache write #4 | newObject=true | entries=2 | entriesReallyChanged=0
AFTER (with the change below)
no cache writes
That's two state writes per toggle with nothing changed: one when isOffline changes, and another one render later when prevIsOffline catches up.
How this turns into the loop:
- When
getUpdatedReports()returns nothing, the memo re-checks every displayed report (useSidebarOrderedReports.tsx#L235), so any recompute goes through the code above. - The result is always new, so the effect at L328 sets state and the provider renders again.
- Several memo inputs are "previous value" helpers (
usePrevious,useCollectionDelta,prevReportAttributes) that only catch up one render later, so the extra render changes them again and the memo recomputes, which allocates again. On/searchthe provider gets a burst of report, transaction and report attribute updates while results load, and with nothing ever bailing out these cascades pile up past React's nested update limit.
About the snapshot idea: SidebarOrderedReportsContextProvider is mounted in AuthScreens (AuthScreens.tsx#L192), outside SearchScopeProvider (Search/index.tsx#L1435). So useIsOnSearch() is false inside it and its useOnyx(ONYXKEYS.COLLECTION.REPORT) never reads the search snapshot. Also, a shallow-compare guard on the effect would not stop it, because the flagged entries themselves are new objects each time, so the shallow compare still sees a change.
What changes do you think we should make in order to solve the problem?
- In
SidebarUtils, remember which report each flagged entry was copied from (a module-levelWeakMap<entry, Report>). Build flagged entries through one helper in bothgetReportsToDisplayInLHNandupdateReportsToDisplayInLHN, and in the update path reuse the existing entry when its source report and the three flags are unchanged:
const sourceReportByLHNEntry = new WeakMap<object, Report>();
function buildFlaggedLHNEntry(report: Report, flags: LHNEntryFlags) {
const entry = {...report, ...flags};
sourceReportByLHNEntry.set(entry, report);
return entry;
}
function isSameFlaggedLHNEntry(entry, report, flags) {
return !!entry && sourceReportByLHNEntry.get(entry) === report
&& entry.requiresAttention === flags.requiresAttention
&& entry.hasErrorsOtherThanFailedReceipt === flags.hasErrorsOtherThanFailedReceipt
&& entry.isUnreadReport === flags.isUnreadReport;
}
// updateReportsToDisplayInLHN
if (hasFlags && !isSameFlaggedLHNEntry(existingEntry, report, flags)) {
getMutableCopy()[reportID] = buildFlaggedLHNEntry(report, flags);
}
With that, a recompute with no real change returns the same map, so the effect doesn't fire, setCurrentReportsToDisplay isn't called, and the chain never starts. The WeakMap lets old entries be garbage collected.
2. Keep the effect as is. It only needs to run when the map really changes, which it now does.
What specific scenarios should we cover in automated tests?
updateReportsToDisplayInLHNreturns the same object and entry when called again with unchanged inputs and a flagged report (fails on main today).- It still returns a new entry when the report or one of the flags changes.
useSidebarOrderedReports: re-rendering the provider with no data changes does not callsetCurrentReportsToDisplaywith a new value.
What alternative solutions did you explore? (Optional)
- Keep the cache in a
useRefinstead ofuseState, so updating it never schedules a render. That removes the extra render entirely, but it changes howclearLHNCacheworks, so I'd keep it as a follow-up. - A shallow-compare guard in the effect. It does not help here because the flagged entries are new objects every time.
@parasharrajat a quick timing note for the review. The flagged entry root cause (existingEntry !== report always true at SidebarUtils L451) and the WeakMap fix with sourceReportByLHNEntry / buildFlaggedLHNEntry were first posted in my proposal at 00:16 UTC, with the before/after numbers from the app. The update above came 15 minutes later with the same names, and the earlier proposal from the same author pointed to the search snapshot instead. Thanks!
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~011091133bbb09cd1c
Proposal
Please re-state the problem that we are trying to solve in this issue.
On web, predominantly on /search and /search/r/:reportID, the application crashes with a fatal React error:
Error: Maximum update depth exceeded (React #185) originating from useSidebarOrderedReports.tsx:328 useEffect -> setCurrentReportsToDisplay(reportsToDisplayInLHN).
What is the root cause of that problem?
The infinite render loop is caused by a broken referential equality check in SidebarUtils.updateReportsToDisplayInLHN that prevents the LHN cache from ever settling when at least one displayed report has flags (unread, requires attention, or errors).
1. The Broken Lazy Copy in SidebarUtils.ts:451:
In src/libs/SidebarUtils.ts:401-460:
// Use a lazy copy to avoid creating a new object reference when no entries actually change.
let displayedReportsCopy: ReportsToDisplayInLHN | undefined;
const getMutableCopy = (): ReportsToDisplayInLHN => {
if (!displayedReportsCopy) {
displayedReportsCopy = {...displayedReports};
}
return displayedReportsCopy;
};
...
if (hasFlags) {
if (
existingEntry !== report ||
existingEntry?.requiresAttention !== requiresAttention ||
existingEntry?.hasErrorsOtherThanFailedReceipt !== hasErrorsOtherThanFailedReceipt ||
existingEntry?.isUnreadReport !== isUnreadReport
) {
getMutableCopy()[reportID] = {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport};
}
} else if (existingEntry !== report) {
getMutableCopy()[reportID] = report;
}
- For any report with flags (
requiresAttention,hasErrorsOtherThanFailedReceipt, orisUnreadReport), line 456 stores a cloned object literal{...report, ...flags}indisplayedReports. - On any subsequent update pass, line 451 performs:
existingEntry !== report - Because
existingEntryis the previously cloned object on the JS heap whilereportis the Onyx report reference,existingEntry !== reportalways evaluates totrue. - As a consequence,
getMutableCopy()is invoked on every single pass whenever any flagged report exists, allocating a brand-newdisplayedReportsCopydictionary and allocating fresh object clones for every flagged report, even when neither the report data nor any flags changed.
2. The Cascading Render Cycle in useSidebarOrderedReports.tsx:
useSidebarOrderedReportscomputesreportsToDisplayInLHNin auseMemo(line 229). BecauseupdateReportsToDisplayInLHNperpetually returns a new dictionary object reference with newly allocated entries,reportsToDisplayInLHNis referentially unstable.- In
useSidebarOrderedReports.tsx:327-329:
BecauseuseEffect(() => { setCurrentReportsToDisplay(reportsToDisplayInLHN); }, [reportsToDisplayInLHN]);reportsToDisplayInLHNchanged reference, the effect runs and callssetCurrentReportsToDisplay(reportsToDisplayInLHN). - Updating this state triggers an immediate re-render of
SidebarOrderedReportsContextProvider. - Several dependencies of
getUpdatedReportsare previous-value trackers (useCollectionDelta,usePrevious(derivedCurrentReportID),usePrevious(isOffline),reportAttributesUpdates) whose refs only update in auseEffectthat fires after commit. Therefore, the re-render triggers another dependency change ingetUpdatedReportsone render later. - In line 235:
Whenlet effectiveUpdatedReports = updatedReports.length === 0 && hasCachedReports ? Object.keys(currentReportsToDisplay) : updatedReports;updatedReportsis empty,effectiveUpdatedReportsrechecks all displayed reports, which re-invokesupdateReportsToDisplayInLHNon every displayed report, triggering the flagged copy bug again and generating yet another new dictionary.
3. Why This Crashes on /search:
On /search and /search/r/:reportID, rapid async bursts of transactions, search result snapshots, and report route transitions occur concurrently. Because the LHN cache mechanism never settles into an identity match, these cascading renders pile up concurrently without ever bailing out, rapidly exceeding React's nested update limit of 50.
(Note: The existing unit test in tests/unit/SidebarUtilsTest.ts:4680 passed because it tested an imaginary key report999 not in displayedReports, bypassing the report loop entirely.)
What changes do you think we should make in order to solve the problem?
We propose a robust, two-layered solution:
Layer 1: Referential Source Tracking in src/libs/SidebarUtils.ts
Track the original report reference for each flagged entry via a module-level WeakMap. This eliminates memory leaks, avoids polluting the Report schema or runtime object keys, and allows isSameFlaggedLHNEntry to detect whether the underlying report or flags have genuinely changed.
--- a/src/libs/SidebarUtils.ts
+++ b/src/libs/SidebarUtils.ts
@@ -253,6 +253,27 @@ let isFirstTimeNewReportInAccessible = true;
let lastReportsToDisplayInLHN: ReportsToDisplayInLHN | undefined;
+
+type LHNEntryFlags = {
+ requiresAttention: boolean;
+ hasErrorsOtherThanFailedReceipt: boolean;
+ isUnreadReport: boolean;
+};
+
+const sourceReportByLHNEntry = new WeakMap<object, OnyxTypes.Report>();
+
+function buildFlaggedLHNEntry(report: OnyxTypes.Report, flags: LHNEntryFlags): OnyxTypes.Report & LHNEntryFlags {
+ const entry = {...report, ...flags};
+ sourceReportByLHNEntry.set(entry, report);
+ return entry;
+}
+
+function isSameFlaggedLHNEntry(
+ existingEntry: (OnyxTypes.Report & LHNEntryFlags) | undefined,
+ report: OnyxTypes.Report,
+ flags: LHNEntryFlags,
+): boolean {
+ if (!existingEntry) {
+ return false;
+ }
+ const sourceReport = sourceReportByLHNEntry.get(existingEntry) ?? existingEntry;
+ return (
+ sourceReport === report &&
+ existingEntry.requiresAttention === flags.requiresAttention &&
+ existingEntry.hasErrorsOtherThanFailedReceipt === flags.hasErrorsOtherThanFailedReceipt &&
+ existingEntry.isUnreadReport === flags.isUnreadReport
+ );
+}
@@ -353,7 +374,7 @@ function getReportsToDisplayInLHN({
if (shouldDisplay) {
const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false;
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty);
reportsToDisplay[reportID] =
- requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport ? {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport} : report;
+ requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport ? buildFlaggedLHNEntry(report, {requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport}) : report;
}
}
@@ -448,15 +469,10 @@ function updateReportsToDisplayInLHN({
const hasFlags = requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport;
const existingEntry = displayedReports[reportID];
if (hasFlags) {
- if (
- existingEntry !== report ||
- existingEntry?.requiresAttention !== requiresAttention ||
- existingEntry?.hasErrorsOtherThanFailedReceipt !== hasErrorsOtherThanFailedReceipt ||
- existingEntry?.isUnreadReport !== isUnreadReport
- ) {
- getMutableCopy()[reportID] = {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport};
+ if (!isSameFlaggedLHNEntry(existingEntry, report, {requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport})) {
+ getMutableCopy()[reportID] = buildFlaggedLHNEntry(report, {requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport});
}
} else if (existingEntry !== report) {
getMutableCopy()[reportID] = report;
}
Layer 2: Defensive State Bail-Out in src/hooks/useSidebarOrderedReports.tsx
Guard setCurrentReportsToDisplay with shallow dictionary comparison:
--- a/src/hooks/useSidebarOrderedReports.tsx
+++ b/src/hooks/useSidebarOrderedReports.tsx
@@ -326,7 +326,17 @@ function SidebarOrderedReportsContextProvider({
}, [reportsDrafts]);
useEffect(() => {
- setCurrentReportsToDisplay(reportsToDisplayInLHN);
+ setCurrentReportsToDisplay((prev) => {
+ if (prev === reportsToDisplayInLHN) {
+ return prev;
+ }
+ const prevKeys = Object.keys(prev);
+ const nextKeys = Object.keys(reportsToDisplayInLHN);
+ if (prevKeys.length === nextKeys.length && nextKeys.every((key) => prev[key] === reportsToDisplayInLHN[key])) {
+ return prev;
+ }
+ return reportsToDisplayInLHN;
+ });
}, [reportsToDisplayInLHN]);
Why both layers:
- Layer 1 preserves referential identity of unchanged flagged entries, allowing
displayedReportsCopyto stayundefinedsoupdateReportsToDisplayInLHNreturns the originaldisplayedReportsreference. - Layer 2 provides defense-in-depth: if any upstream dependency recomputes and produces a new dictionary container, React immediately detects that all entry references are identical and bails out of updating state.
What specific scenarios should we cover in automated tests to prevent reintroduction of this issue in the future?
-
tests/unit/SidebarUtilsTest.ts:- Call
updateReportsToDisplayInLHNwith a report that hasrequiresAttention: trueorisUnreadReport: true. - Call
updateReportsToDisplayInLHNa second time with the exact same inputs and report reference. - Assert
expect(result2).toBe(result1)(currently fails onmain). - Call
updateReportsToDisplayInLHNwith updated report properties or changed flag values; assertexpect(result3).not.toBe(result2)and the updated flag is reflected.
- Call
-
tests/unit/useSidebarOrderedReportsTest.tsx:- Render
SidebarOrderedReportsContextProviderwith an unread chat in the LHN. - Simulate a re-render or trigger an unrelated collection update that doesn't modify the displayed chat.
- Assert
setCurrentReportsToDisplaydoes not trigger cascading re-renders or exceed React's maximum update depth.
- Render
What alternative solutions did you explore? (Optional)
- Only using a shallow equality check in
useSidebarOrderedReports.tsx:- As explained above, shallow compare on its own does not work without Layer 1 because
updateReportsToDisplayInLHNgenerates freshly cloned entry objects{...report, ...flags}on every pass, causingprev[key] === next[key]to fail for every flagged report.
- As explained above, shallow compare on its own does not work without Layer 1 because
- Replacing
currentReportsToDisplayuseStatewithuseRef:- While storing
currentReportsToDisplayin a ref avoids scheduling renders,useSidebarOrderedReportsState()exposesorderedReportIDsand related state to consumers, and altering state synchronization would breakclearLHNCacheand downstream consumers.
- While storing
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@parasharrajat here's a test branch for my proposal: https://github.com/Expensify/App/compare/main...stacklancer:App:fix/104504-lhn-cache-identity
It has the SidebarUtils change plus unit tests for flagged entries (same object when nothing changed, new entry when the report changes, and entries from a full rebuild are reused). The new tests fail on main and pass on the branch, and the existing LHN/sidebar suites still pass. In the app, toggling Force offline now causes no cache writes instead of four.
@parasharrajat Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
Proposal
Please re-state the problem that we are trying to solve in this issue.
The sidebar provider can crash with React's Maximum update depth exceeded. The reported stack points to the effect that copies reportsToDisplayInLHN into currentReportsToDisplay, particularly while navigating /search and /search/r/:reportID.
What is the root cause of that problem?
The provider schedules a React update to maintain an internal previous-result cache, feeding a derived result back into its own computation. In useSidebarOrderedReports.tsx, currentReportsToDisplay is state, but it is only read as the starting cache for the next reportsToDisplayInLHN calculation. The context, sorting, filtering, counts and bulk actions use the current memo result, not that cache. The effect at lines 329–331 nevertheless calls setCurrentReportsToDisplay whenever the memo returns a different reference.
There is a concrete allocation problem that amplifies this feedback: SidebarUtils.ts stores flagged reports as {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport}, then compares that clone with the source report using existingEntry !== report. This remains true on a later pass even if the report and all three flags are unchanged. The incremental updater allocates a new entry and map, defeating its lazy-copy bailout. A full rebuild also returns a new map, including when the result is empty.
The cache-state update causes another render. usePrevious and useCollectionDelta inputs can change as their previous values catch up after the preceding commit, invalidating getUpdatedReports and the memo again. When no report-specific delta remains, the memo explicitly rechecks all cached entries, reaching the clone comparison again.
This establishes the unnecessary feedback path and a reproducible identity defect; it does not establish that one unchanged flagged report alone causes an unbounded loop. Previous-value hooks can settle. The exact production sequence that keeps invalidating the memo is unavailable in the issue. The fix should remove the self-scheduled update regardless of that trigger, rather than require every dependency to retain its identity.
What changes do you think we should make in order to solve the problem?
Keep the previous committed map in a ref, and continue rendering from reportsToDisplayInLHN. This is a small, provider-local fix:
-
Replace the cache state declaration with:
const currentReportsToDisplayRef = useRef<ReportsToDisplayInLHN>({}); -
At the start of the existing memo, read
const currentReportsToDisplay = currentReportsToDisplayRef.current;. Keep the full/incremental calculations and their actual input dependencies unchanged. The ref is a previous-result cache, not a new dependency or a replacement for the memo's return value. -
Replace the cache-writing effect with:
useEffect(() => { currentReportsToDisplayRef.current = reportsToDisplayInLHN; }, [reportsToDisplayInLHN]);Commit the cache in the effect, not by mutating it inside
useMemo: an abandoned render should not publish a speculative cache. This assignment schedules no render, removing theeffect → setStateedge from the reported crash. -
Preserve
clearLHNCacheexplicitly:currentReportsToDisplayRef.current = {}; setClearCacheDummyCounter((current) => current + 1);The existing counter remains a memo dependency and forces the next calculation to rebuild. Keep the other state hooks: the counter and sticky selection still require React updates. Update the old cache comments/lint explanation to describe the ref.
The render uses the new memo result immediately; it does not wait for the cache effect. orderedReportIDs, tab filters/counts, sticky reports and inboxTabSourcesRef retain their current data flow. Removing this cache's state setter does not remove consumer updates or disable manual invalidation.
Regression coverage: exercise full and incremental results, including deliberately fresh but equivalent maps on triggered calculations; cache commits must not schedule another render. Change a real report/flag and confirm order, visibility and counts update. Clear populated and empty caches and verify a rebuild. Cover unread/error/attention entries, flag removal, deleted reports, route changes, reconnect, late guide hydration and Strict Mode.
What alternative solutions did you explore? (Optional)
- Shallow equality on the state setter: fails when flagged entries themselves are fresh clones. Deep equality adds whole-map work and retains a second state-update path for real changes.
- Source-reference tracking for decorated entries: addresses the verified
SidebarUtilsallocation defect and is useful as a separate optimization. It must cover both builders and retain changes to all source fields, not just flags orlastVisibleActionCreated. It is unnecessary to remove the cache's React feedback; I would not bundle a new module-level cache into this minimal crash fix. - Removing
existingEntry !== report, adding the cache to memo dependencies, or suppressing dependency changes: respectively risks stale report fields, creates direct feedback, or misses legitimate sidebar updates.
@parasharrajat 6 days overdue. This is scarier than being forced to listen to Vogon poetry!
@parasharrajat 8 days overdue is a lot. Should this be a Weekly issue? If so, feel free to change it!
@parasharrajat friendly bump when you get a chance. My proposal and test branch are ready for review, happy to answer any questions.
@parasharrajat 12 days overdue now... This issue's end is nigh!
@parasharrajat 12 days overdue. Walking. Toward. The. Light...
@parasharrajat 12 days overdue. Walking. Toward. The. Light...
@parasharrajat what is the latest here?
@parasharrajat 12 days overdue now... This issue's end is nigh!