Skip to content

Optimize state updates with structural sharing on frontend - #7273

Merged
masenf merged 6 commits into
mainfrom
farhan/sleepy-hawking-bhua3z
Oct 9, 2026
Merged

masenf merged 6 commits into
mainfrom
farhan/sleepy-hawking-bhua3z

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Type of change

  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update

Changes To Core Features

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Description

This PR improves frontend performance by implementing structural sharing in the applyDelta function. When state updates are applied, unchanged objects and arrays now retain their previous identity, allowing memoized React components to skip re-rendering and enabling identity-based caches to continue hitting.

Key changes:

  1. Added isPlainObject helper — Distinguishes plain objects from arrays, Dates, and class instances to determine which values should participate in structural sharing.

  2. Added replaceEqualDeep function — Recursively compares previous and next values, preserving object/array identity when contents are unchanged. This is the core of the structural sharing optimization:

    • For arrays: shares unchanged elements and handles length changes efficiently
    • For plain objects: shares unchanged properties and handles added/removed keys
    • For other types: returns the new value as-is
  3. Refactored applyDelta — Now uses replaceEqualDeep to build a new state object only when necessary. If no keys changed, returns the original state object unchanged, preventing unnecessary re-renders.

Benefits:

  • Memoized components (via React.memo) skip re-rendering when their props haven't actually changed
  • Identity-based caches and optimizations continue to work across updates
  • An update that changes nothing returns the same state object, skipping the render entirely
  • Handles edge cases like __proto__ keys from JSON safely

Test Plan

Added comprehensive Node.js-based tests in test_apply_delta_shares_unchanged_values that verify:

  • Identity preservation for unchanged nested objects and arrays
  • Proper handling of array length changes
  • Key additions, removals, and renames
  • Type changes and non-plain values
  • Security: __proto__ keys remain as own data properties

All tests pass with Node.js runtime validation.

Review in cubic

Each delta from the backend is freshly parsed JSON, so even unchanged
fields arrived with new identities and defeated every identity-based
memo comparison. applyDelta now merges each delta value into the
previous one, keeping the old plain object or array wherever the
contents are deep-equal, and returns the same state object when a delta
changes nothing so useReducer bails out of the render.

Only plain objects and arrays are shared; everything else is replaced as
before. New containers are allocated only once a difference is found.

Claude-Session: https://claude.ai/code/session_01TqoG8S2SYfnDSTBzXNRf7C
@FarhanAliRaza
FarhanAliRaza requested a review from a team as a code owner September 22, 2026 20:17
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T20:24:01.296357Z 9873f0b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Optimizes state update logic on the frontend.

This PR appears safe to merge based on the reviewed changes.

Summary

The PR adds structural sharing to frontend state updates and tests identity preservation, key ordering, numeric equality, and nested __proto__ handling.

Reviews (2) · Last reviewed commit: "Assert the extracted state.js helpers co..."

Comment thread packages/reflex-base/src/reflex_base/.templates/web/utils/state.js Outdated

@cubic-dev-ai cubic-dev-ai Bot 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.

1 issue found across 3 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/units/compiler/test_state_js_template.py">

<violation number="1" location="tests/units/compiler/test_state_js_template.py:131">
P3: This test extracts the template helpers by slicing the file between literal marker strings (`content.index("const isPlainObject =")` / `content.index("export const evalReactComponent =")`). Any future edit that mentions `evalReactComponent` before its definition, renames it, or restructures the file silently truncates the window (dropping `applyDelta`, so node fails with an unhelpful ReferenceError) or raises a bare ValueError. The repo already flagged delimiter-based source splitting in previous reviews; follow that guidance and locate `applyDelta` by parsing state.js with the installed Rolldown parser instead. At minimum, assert the sliced chunk actually contains `export const applyDelta` so a moved marker fails loudly at the extraction point.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread packages/reflex-base/src/reflex_base/.templates/web/utils/state.js Outdated
Comment thread packages/reflex-base/src/reflex_base/.templates/web/utils/state.js
Comment thread tests/units/compiler/test_state_js_template.py

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9873f0b1f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/reflex-base/src/reflex_base/.templates/web/utils/state.js Outdated
@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 147 untouched benchmarks
⏩ 17 skipped benchmarks1


Comparing farhan/sleepy-hawking-bhua3z (b8727b1) with main (02efed7)

Open in CodSpeed

Footnotes

  1. 17 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@cubic-dev-ai cubic-dev-ai Bot 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.

All reported issues were addressed

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread packages/reflex-base/src/reflex_base/.templates/web/utils/state.js

@masenf masenf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is definitely a behavior change and i'm not 100% sure it's what we want. in #7084 (not merged yet) i added a by_value kwarg to rx.memo which opts in to this kind of behavior at the memo level -- so the delta will still cause a re-render when it comes in, but opted in memo components won't re-render when their props have the same value.

this approaches it at a higher layer, so the optimization applies to all stateful components, but it requires deep checking every delta that comes in to make that determination.

there could also theoretically be apps out there that implicitly depend on re-renders for retriggering certain effects which could subtly break.

@masenf masenf added the perf Performance-improving changes label Sep 29, 2026
No conflicts; state.js auto-merged with main's event normalization helpers
placed before the new delta helpers.

Claude-Session: https://claude.ai/code/session_01PXcFKAgnzhgdnSvhuCmxWE
Strict equality dropped a 0 -> -0 update (python sends -0.0) and treated a
repeated NaN, revived by parseJson, as a change on every delta.

Claude-Session: https://claude.ai/code/session_01PXcFKAgnzhgdnSvhuCmxWE
A dict reordered with the same values reused the previous object, so the UI
kept the old key order; prev is now only reused when the keys match in order.

Claude-Session: https://claude.ai/code/session_01PXcFKAgnzhgdnSvhuCmxWE
A moved marker now fails at the extraction point instead of as a node
ReferenceError.

Claude-Session: https://claude.ai/code/session_01PXcFKAgnzhgdnSvhuCmxWE
@masenf masenf added the on deck PRs lined up to review / merge next label Oct 5, 2026
@masenf
masenf merged commit 7b13fc7 into main Oct 9, 2026
148 checks passed
@masenf
masenf deleted the farhan/sleepy-hawking-bhua3z branch October 9, 2026 18:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on deck PRs lined up to review / merge next perf Performance-improving changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants