Skip to content

Inside an @rx.memo body, hooks of rx.cond / rx.foreach children are hoisted: cond on_mount fires unconditionally, foreach items crash the page #7836

Open

Description

@masenf

Problem

In page compilation, a component with instance hooks (on_mount / on_unmount, add_hooks, refs) that sits under rx.cond or inside rx.foreach gets its own wrapper, so its hooks run only when the branch is shown, and once per loop item (0.11 added the per-item part in #7792 / #7793). Inside the body of an @rx.memo component this does not happen: the memo body is compiled with render._get_all_hooks(), which hoists every descendant's hooks to the top of the memo function. Two visible failures follow.

  1. rx.cond in a memo body: the hidden branch's on_mount fires when the memo mounts, and toggling the condition fires nothing (neither on_unmount of the old branch nor on_mount of the new one). The 0.11 changelog line "on_mount and on_unmount still follow their rx.cond branch" holds only outside @rx.memo.
  2. rx.foreach in a memo body with item hooks: the hoisted hook references the loop variable outside the loop, so the whole page falls into the error boundary with ReferenceError: it_rx_state_ is not defined (dev and prod). The changelog calls this "not covered yet"; in practice it is a page crash, not wrong counts.

Not a regression (0.10.1 behaves the same), but 0.11 documents per-row client state and memo rows, so these patterns are now encouraged.

Repro

import reflex as rx


class S(rx.State):
    flag: bool = True
    items: list[str] = ["alpha", "beta", "gamma"]
    log: list[str] = []

    @rx.event
    def record(self, what: str):
        self.log.append(what)

    @rx.event
    def toggle(self):
        self.flag = not self.flag


@rx.memo
def memo_cond(show: rx.Var[bool], label: rx.Var[str]) -> rx.Component:
    return rx.box(
        rx.cond(
            show,
            rx.text("shown-", label, on_mount=S.record("m:" + label), on_unmount=S.record("u:" + label)),
        )
    )


@rx.memo
def memo_loop(items: rx.Var[list[str]]) -> rx.Component:
    return rx.vstack(
        rx.foreach(items, lambda it: rx.text(it, on_mount=S.record("m:" + it)))
    )


def cond_page():
    return rx.vstack(
        rx.button("toggle", on_click=S.toggle),
        memo_cond(show=S.flag, label="x"),
        memo_cond(show=~S.flag, label="y"),
        rx.text(S.log.join(",")),
    )


def loop_page():
    return memo_loop(items=S.items)


app = rx.App()
app.add_page(cond_page, route="/cond")
app.add_page(loop_page, route="/loop")
  • /cond: log shows m:x,m:y at mount although only x is shown; clicking toggle adds nothing. Writing the same rx.cond directly in the page (no memo) gives m:x, then u:x,m:y, which is correct.
  • /loop: error boundary, ReferenceError: it_rx_state_ is not defined.

Expected

Hooks of a descendant under rx.cond / rx.foreach inside an @rx.memo body follow the same rules as in a page: they run in the branch / per item, not at the memo's top level.

Fix direction

  • Code: the memo-body compile in reflex/compiler/utils.py (the place that builds the memo function with hooks = render._get_all_hooks()), compared with the page path that inserts wrapper boundaries for instance-hook descendants of Cond / Foreach (the auto-memoize plugin's handling from Run the hooks of an rx.foreach item inside the loop body #7792 / Pass loop variables to auto-memo wrappers inside rx.foreach #7793).
  • Reuse the same boundary insertion for memo bodies: a Cond branch or Foreach item that carries instance hooks becomes its own small component inside the memo module, so its hooks are scoped to it.
  • Constraints: hooks that genuinely belong to the memo's own root (not under a Cond/Foreach) must stay at the top of the memo function; generated output must stay reproducible (no per-build random names). Watch compile time on large apps; Warn when an unkeyed rx.foreach item has lifecycle events or hooks #7820 moved a similar check into the plugin's existing walk for that reason.
  • If a full fix is too large, an interim compile-time error naming the memo function and the offending child is better than the runtime crash for the rx.foreach case.
  • Tests: compiler unit tests asserting the generated memo code scopes the hooks, plus a Playwright check of the two pages above.

Activity

  1. added
    bugSomething isn't working
    release-trainIssues found during agentic /prerelease-testing fanout, not necessarily validated bugs.
    on Nov 11, 2026
  2. linear-code commented on Nov 11, 2026

    @linear-code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingrelease-trainIssues found during agentic /prerelease-testing fanout, not necessarily validated bugs.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions