Skip to content

Run the hooks of an rx.foreach item inside the loop body - #7792

Closed
FarhanAliRaza wants to merge 3 commits into
mainfrom
farhan/foreach-item-hooks
Closed

FarhanAliRaza wants to merge 3 commits into
mainfrom
farhan/foreach-item-hooks

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7791

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Problem

A hook of a component inside rx.foreach was hoisted to the top of the Foreach memo body, outside the loop:

rx.foreach(S.items, lambda x: rx.text(x, on_mount=S.seen(x)))
const Foreach_comp_... = memo(({children}) => {
  useEffect(() => { ...seen({ x: x_rx_state_ }) }, []);   // x_rx_state_ does not exist here
  return items.map((x_rx_state_, index) => jsx(Text, {key: index}, x_rx_state_))
});
  • A hook that read the loop variable crashed the page: ReferenceError: x_rx_state_ is not defined.
  • A hook that did not read it ran once for the whole list, not once per item.

This applied to on_mount, on_unmount, and hooks from add_hooks.

Fix

When an item has such hooks, Foreach compiles the item to a component at module level, in the same generated file, and passes the loop variables as props:

const ForeachItem_<hash> = (({x_rx_state_, index}) => {
  useEffect(() => { ...seen({ x: x_rx_state_ }) }, []);
  return (jsx(Text, {key: index}, x_rx_state_))
});

items.map((x_rx_state_, index) => jsx(ForeachItem_<hash>, {key: index, x_rx_state_, index}))

The hooks belong to one item, and the loop variables are in scope. The item component also receives the variables that the enclosing generated code binds: the loop variables of enclosing rx.foreach loops and the parameters of an enclosing @rx.memo function. The hooks that the item key needs stay in the outer scope, because the loop body evaluates the key there.

An item gets its own component only when:

  • a component in it has a lifecycle event, _get_hooks, or add_hooks, or
  • one of its hooks reads the loop variable or the index variable.

All other loops compile to the same code as before.

The item component is a normal top-level function component, so React Compiler accepts it. A first version called the hooks in a function expression inside .map(); React Compiler rejects that ("Hooks must be called at the top level").

Testing

  • New unit tests in tests/units/compiler/test_memoize_plugin.py: on_mount, add_hooks and index-variable items, a nested loop that reads the outer loop variable, a state-backed item key, a lifecycle event in a prop component, a loop inside a memo function, and an item without such hooks.
  • tests/units/compiler and tests/units/components/core: 520 passed. All unit tests that match memo or foreach: 434 passed.
  • Live check, reflex run --env prod, Chromium, default config:
    • Each item fires its own on_mount, also in a nested loop.
    • A new item fires only its own on_mount. A removed item fires its on_unmount.
    • An unrelated state update fires nothing, and an input inside an item keeps its text.
    • No console errors.
  • React Compiler (the experimental release and plugin settings from ENG-12682 Let React Compiler optimize generated components #7694) on the generated memo module: the item components and the Foreach components compile, with no hook errors.

Known limits

  • The item component receives loop variables and memo parameters. A value that a raw hook string declares in the enclosing function, and that the item reads without that hook in its VarData, is not in scope in the item component.

A hook of a component inside rx.foreach was hoisted to the top of the
Foreach memo body. A hook that read the loop variable crashed the page with
a ReferenceError, and lifecycle events fired once for the whole list.

When an item has such hooks, render it through ForeachItem, a runtime
component that calls the item's hooks and returns its element.

Fixes #7791
@FarhanAliRaza
FarhanAliRaza requested a review from a team as a code owner November 10, 2026 19:28
@FarhanAliRaza FarhanAliRaza added the on deck PRs lined up to review / merge next label Nov 10, 2026
@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change affects generated frontend behavior for hooked `rx.foreach` items.

The PR still needs the embedded-list rendering path fixed before merging.

Summary

The PR gives hooked rx.foreach items their own module-level components.

The latest changes:

  • Hooks in a rx.foreach item run with that item's loop values.

FarhanAliRaza documents a known limit: values declared by an outer item’s hook are not passed to an inner item unless their VarData carries the hook.

Reviews (3) · Last reviewed commit: "Keep an rx.foreach item component in sco..." · Reviewed by Greptile

@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 6 files

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

View guided diff | Turn on auto-fix | Re-trigger cubic

@codspeed

codspeed Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 12.36%

2 warnings

⚠️ 14 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 3 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

❌ 3 regressed benchmarks
✅ 148 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_evaluate_page[_stateful_page] 7.1 ms 8.5 ms -16.39%
❌ test_evaluate_page_with_hooks[_stateful_page] 7.5 ms 8.9 ms -15.47%
❌ test_process_event_burst_independent_tokens[1] 2.7 ms 2.9 ms -4.77%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing farhan/foreach-item-hooks (08ee64c) with main (58e7128)

Open in CodSpeed

React Compiler rejects hooks that are called in a function expression, so
the render closure left the Foreach memo component unoptimized. Emit the
item as a component at module level and pass the loop variables, including
those of enclosing loops, as props.

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

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_memoize_plugin.py">

<violation number="1" location="tests/units/compiler/test_memoize_plugin.py:565">
P2: This assertion no longer rejects the legacy `ForeachItem` runtime component, so a regression from inline rendering to that component would pass the test. Keep the broader `"ForeachItem"` check.</violation>
</file>

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

View guided diff | Turn on auto-fix | Re-trigger cubic

lambda: rx.foreach(SpecialFormMemoState.items, lambda item: rx.text(item))
)

assert "ForeachItem_" not in code

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.

P2: This assertion no longer rejects the legacy ForeachItem runtime component, so a regression from inline rendering to that component would pass the test. Keep the broader "ForeachItem" check.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. 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. At tests/units/compiler/test_memoize_plugin.py, line 565:

<comment>This assertion no longer rejects the legacy `ForeachItem` runtime component, so a regression from inline rendering to that component would pass the test. Keep the broader `"ForeachItem"` check.</comment>

<file context>
@@ -536,7 +562,7 @@ def test_foreach_item_without_scoped_hooks_renders_inline() -> None:
     )
 
-    assert "ForeachItem" not in code
+    assert "ForeachItem_" not in code
 
 
</file context>
Suggested change
assert "ForeachItem_" not in code
assert "ForeachItem" not in code

- Declare the hooks of the item key where the loop body evaluates the key.
- Pass memo function parameters to the item component, next to the loop
  variables of enclosing loops.
- Detect lifecycle events of components that an item holds in a prop.
@FarhanAliRaza

Copy link
Copy Markdown
Contributor Author

Superseded by #7793, which fixes #7791 through the auto-memo system: loop variables are carried in VarData.deps and passed to the wrapper as props, instead of a separate ForeachItem_<hash> component.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

on_mount inside rx.foreach that uses the loop variable crashes the page

1 participant