Skip to content

ENG-12682 Let React Compiler optimize generated components - #7272

Closed
FarhanAliRaza wants to merge 4 commits into
reflex-dev:codex/react-compiler-opt-infrom
FarhanAliRaza:farhan/react-compiler-generation
Closed

FarhanAliRaza wants to merge 4 commits into
reflex-dev:codex/react-compiler-opt-infrom
FarhanAliRaza:farhan/react-compiler-generation

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #7234.

React Compiler bailed out on most generated pages and memo wrappers because of patterns Reflex emits. This PR changes those patterns. It also adds an auto_memoize option, so an app using react_compiler can let the compiler memoize whole pages instead of Reflex's generated memo wrappers.

Changes

Bailout Fix
refs["ref_x"] = ref_x during render ("This value cannot be modified") const ref_x = useRegisteredRef("ref_x"). The hook lives in utils/state.js, outside compiler scope, and keeps the same registry behavior.
useMemo(generateUUID, []) ("Expected the first argument to be an inline function expression") useMemo(() => generateUUID(), [])
useCallback deps list addEvents, ReflexEvent, and unused hook bindings such as setFilesById ("Found extra memoization dependencies") Only bindings the callback references
Capture-free (...args) => addEvents(...) handlers crash function outlining ("Expected temporaries to be promoted") enableFunctionOutlining: false
jsx(type, props, ...children) from Emotion is an unknown function, so compiled pages cannot cache elements (33 vs 280 cache slots on the test dashboard) moduleTypeProvider describing jsx like JSX syntax: frozen arguments, frozen result

The experimental compiler (0.0.0-experimental-a1856f3-20260507) is required. 1.0.0 still rejects refs passed to jsx() and optional calls in ternary tests.

auto_memoize=False removes MemoizeStatefulPlugin from page compilation. App-root memoization is unchanged.

Measurements

Production builds, Chromium, direct state dispatch, 11 alternating rounds × 100 updates. Dashboard page: sidebar, 8 KPI cards, two Recharts charts, tabs with a form and a 10-item list, static cards.

Update Today react_compiler react_compiler + auto_memoize=False
One KPI value 0.87 ms, 171 renders 0.095 ms, 28 renders 0.106 ms, 10 renders
Search input 0.99 ms 0.144 ms 0.163 ms
Chart data 5.90 ms 5.19 ms 5.06 ms
Activity list 0.89 ms 0.33 ms 0.42 ms
Header select 1.06 ms 0.27 ms 0.30 ms

Compiler page coverage with auto_memoize=False: 17/17 stateful pages in a feature fixture, plus 7/8 in a built-in component sweep. The sweep covers Radix, markdown, code, data editor, gridjs, Recharts, Plotly, moment, and event patterns. rx.auto_scroll still bails because its hook code mutates a ref value in render-scope helpers. The app-root Toaster still writes refs['__toast'] during render, and it renders once.

Python compile time with auto-memo off:

App Auto-memo on Auto-memo off
Dashboard fixture 200 ms 128 ms
Feature fixture 179 ms 144 ms
Docs site 42.2 s 31.7 s

Validation

  • Unit suite: 9,731 passed, 19 skipped, 79% coverage. ruff, pyright, and pre-commit pass.
  • Browser checks on both new variants passed with no page errors: rx.set_focus, controlled input round trip, and backend events. The rendered DOM is identical between compiler variants.

Known limits

  • With auto_memoize=False, a page the compiler skips re-renders fully on every state change, about 2× slower than today. The docs say to measure before turning it off.
  • Custom components that inject raw hook JavaScript can still cause bailouts.

Review in cubic

image

Generated code hit React Compiler bailouts that Reflex controls:
render-time writes to the shared refs registry, `useMemo(generateUUID, [])`,
module imports and unused hook bindings listed as useCallback dependencies,
and outlined rest-parameter event handlers. Emotion's `jsx()` calls were
also opaque to the compiler, so compiled components could not cache
elements per input.

- Register id refs through a `useRegisteredRef` hook in utils/state.js.
- Pass `useMemo` an inline callback for generated UUIDs.
- List only referenced bindings as useCallback dependencies.
- Pin the experimental compiler, disable function outlining, and describe
  Emotion's `jsx` via `moduleTypeProvider`.
- Add `auto_memoize` (default True) so apps using `react_compiler` can let
  the compiler memoize whole pages instead of generated memo wrappers.
@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Adds optional auto-memoization toggle and React Compiler integration.

The PR appears safe to merge based on the findings in this review.

Summary

The PR adjusts generated refs, UUID hooks, and event callbacks so React Compiler can optimize more generated components. It also adds auto_memoize to let apps opt out of Reflex’s generated page memo wrappers. No new actionable issue was found in changes made since the previous review.

Reviews (3) · Last reviewed commit: "Clarify the React Compiler news fragment..."

@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 FarhanAliRaza:farhan/react-compiler-generation (4f3e5db) with codex/react-compiler-opt-in (07aa53c)

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. ↩

@FarhanAliRaza
FarhanAliRaza marked this pull request as ready for review September 22, 2026 19:30
@FarhanAliRaza
FarhanAliRaza requested review from a team and Alek99 as code owners September 22, 2026 19:30

@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 across 20 files

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

Re-trigger cubic

Comment thread tests/units/test_config.py Resolved
@FarhanAliRaza FarhanAliRaza changed the title Let React Compiler optimize generated components ENG-12682 Let React Compiler optimize generated components Sep 22, 2026

@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 across 10 files (changes from recent commits).

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

Re-trigger cubic

@masenf masenf added the perf Performance-improving changes label Sep 29, 2026
…-generation

tests/units/reflex_base/templates/test_vite_plugin_react_compiler.py: kept the PR's emotion jsx module-type test and the base's prebundle/prod-react merge test.
tests/units/reflex_base/vars/test_base.py: kept the PR's useMemo inline-callback test and the base's reserved-name/state-root tests.
tests/units/test_prerequisites.py: took the base's assertion derived from REACT_COMPILER_DEV_DEPENDENCIES, which covers the PR's pinned compiler version.

Claude-Session: https://claude.ai/code/session_01VDzz2un9mtjmCY24zSGmca
Client state with Unicode names is not an event handler kind; say what
the change does for it instead of listing it under memoized handlers.

Claude-Session: https://claude.ai/code/session_01VDzz2un9mtjmCY24zSGmca
@masenf masenf added the documentation Improvements or additions to documentation label Oct 6, 2026
@masenf
masenf deleted the branch reflex-dev:codex/react-compiler-opt-in October 14, 2026 07:48
@masenf masenf closed this Oct 14, 2026
FarhanAliRaza added a commit that referenced this pull request Nov 10, 2026
* Let React Compiler optimize generated components

Replays #7272 onto main. That PR auto-closed when its base branch was
deleted after #7234 merged; its own changes were the diff between the
base-branch head it last merged (07aa53c) and its head (4f3e5db),
covering commits c01f4d4, 755ddba and 4f3e5db.

Change the patterns Reflex emits that made React Compiler bail out:
register refs through a useRegisteredRef hook instead of writing to
refs during render, wrap generateUUID in an inline useMemo callback,
list only referenced bindings as useCallback dependencies, disable
function outlining, and describe Emotion's jsx() to the compiler as
JSX. Pin the experimental compiler, which accepts refs passed to jsx().

Add an auto_memoize config option (default True). False removes
MemoizeStatefulPlugin from page compilation so the compiler memoizes
whole pages; app-root memoization is unchanged.

Conflicts with main: #7586 removed hook positions, so the ref hook no
longer passes VarData(position=INTERNAL); #7435 removed
backend_state_mismatch from state.js, so it stays removed.

Claude-Session: https://claude.ai/code/session_01LwJUCTv3FVWzi1UoUpyMLT

* Tie the callback prune pattern to Python names, tidy tests and fragment

Export GENERATED_EVENT_CALLBACK from the React Compiler adapter and test it
against the names get_memoized_event_triggers produces, so a rename on either
side fails a test instead of silently restoring compiler bailouts.

Drop the Unicode stale-callback claim from the reflex-base fragment: main never
had that bug. Move inline test imports to module level.

* Run the auto_memoize compile_app test as a dry run

Without dry_run, REFLEX_SKIP_COMPILE or a leftover .web/nocompile file made
compile_app return before building the page plugins, and the test wrote into
the working directory's .web.

* Derive the client counter test's JS from the var's real identifier (#7741)

test_memo_client_counter hard-coded the JavaScript name a client state
var binds its value to ("Δcounter + 1"). Merging main brought in #6936,
which drops the name of a legacy ClientStateVar created with
global_ref=False and suffixes the emitted identifier with RxClientState,
so the hook now reads `const [cs$0RxClientState, setCs$0] = ...` while
the click handler still read `Δcounter`. That bare identifier resolved
to the button carrying id="Δcounter" through the browser's named
element access, and the counter rendered "[object HTMLButtonElement]1".

Build the increment expression from str(counter.value) instead, with a
{value} placeholder for the direct read and a {source} placeholder for
the eval'd reads, so the test follows whatever identifier Reflex emits.
Use rx.client_state(0) and .set(...) in place of the deprecated
ClientStateVar.create / set_value entry points. rx.client_state rejects
non-ASCII names, so the Unicode case becomes a plain scoped counter;
test_react_compiler_callback_dependencies still covers Unicode bindings
in the Babel dependency prune.


Claude-Session: https://claude.ai/code/session_01ESN8Dfnc4fUrUVcPsqaLGk

Co-authored-by: Claude <noreply@anthropic.com>

* Keep lifecycle events in their branch when auto_memoize is off

Without memo wrappers, on_mount and on_unmount hooks were hoisted to the
page function. A hidden rx.cond branch fired on_mount on page load, and an
rx.foreach item hook read the loop variable outside the loop.

Render the events as a MountEffect element beside the component instead.

* Warn once that react_compiler is experimental

* Render lifecycle events as elements in every compile mode

An on_mount inside rx.foreach was hoisted to the Foreach memo body, where
the loop variable does not exist, so the page crashed. Run
InlineLifecyclePlugin with auto-memoization on as well, and rewrite a
snapshot subtree before the memoize plugin seals it.

* Limit the lifecycle element plugin to the experimental options

Default apps keep the generated code they have on main. The plugin runs
with react_compiler=True or auto_memoize=False.

* Keep scope wrappers when auto_memoize is off; remove MountEffect

The MountEffect element kept one instance across an rx.cond branch switch,
so no lifecycle event fired, and its fragment hid the child from an
as_child parent.

With auto_memoize=False, still wrap a component that has a lifecycle event
or hooks of its own in a memo component. A wrapper has its own identity and
forwards props, and it keeps the hooks in their rx.cond branch.

* Test rx.foreach item lifecycle with auto_memoize off; complete the docstring

- An item's lifecycle hook compiles into a wrapper inside the loop body and
  receives the loop variable when auto_memoize is off.
- default_page_plugins names the snapshot boundary and ALWAYS exceptions.

Claude-Session: https://claude.ai/code/session_01LwJUCVweoEhh1JsZA7emsa

* Keep lifecycle of prop components in a wrapper when auto_memoize is off

With auto_memoize off, a lifecycle event of a component held in a prop moved
into the page function, so it fired on page load even inside a hidden
rx.cond branch. The scope-only rule now uses _has_instance_hooks, which also
checks components held in props.

Claude-Session: https://claude.ai/code/session_01LwJUCVweoEhh1JsZA7emsa

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation perf Performance-improving changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants