Component authoring and rendering
Reflex components let Python code describe a UI tree that the frontend can render with React. A component declaration combines a tag, typed props, child content, events, imports, and optional client-side behavior. The component system turns this declaration into a renderable structure while keeping state-dependent values and custom UI code connected to the generated frontend.
Component model
The component model separates authored UI from the final React output. A component can represent a native element, an imported library component, a fragment of several children, or a value that becomes UI at run time.
Component classes
Component is the main authoring class for UI with props, styles, event triggers, and children. Element supplies the native HTML and SVG family, while NoSSRComponent represents a library component that must load only in the browser. Fragment groups several children without adding a visible container. Bare carries text or a dynamic value without a tag.
These classes support two broad authoring paths:
- Use an existing component factory when the component package already defines the tag and its prop contract.
- Subclass
Componentwhen a UI declaration needs a new tag, prop set, event set, import, or client-side behavior.
The class metadata describes how the declaration should appear in the frontend. The instance holds the values for one use of that declaration. This lets a component class remain reusable while each call supplies different props and children.
References: packages/…/component.py• L336-517 packages/…/component.py• L776-859 packages/…/component.py• L2292-2347 packages/…/element.py• L8-21 packages/…/fragment.py• L6-13 packages/…/bare.py• L57-80
Tags and namespaces
A tag identifies the frontend value that receives props and children. Native elements use their HTML or SVG tag name. Imported components use a library name and an exported tag, with an alias when the Python-facing name must differ from the frontend name.
Component namespaces group related declarations under a shared name. They model APIs with parts such as a root, trigger, content, or item. Each part remains a component with its own child rules and props, so the namespace describes a composable UI family rather than one large component.
The tag layer also carries special render forms. A normal tag has named props and children. A conditional tag selects one of two render values. An iteration tag maps a render function over a state-backed collection. These forms preserve the authored structure until the frontend expression can evaluate it.
References: packages/…/component.py• L524-534 packages/…/component.py• L1182-1240 packages/…/tag.py• L34-105 packages/…/cond_tag.py• L10-31 packages/…/iter_tag.py• L19-35
Component trees
Component calls build a tree from positional children and named props. The tree is the shared input for rendering, style collection, import discovery, hook collection, reference discovery, and event wiring.
Children and composition
Children can be components, text, primitive values, dynamic component values, or nested groups. Text and primitive values become tag-free content. Tuples provide a way to return several children from a helper without forcing the helper to add a visual container.
Child rules can constrain a component family. A component may reject certain child types, allow only named child types, or require a child to appear under a matching parent. Conditional and match wrappers remain valid composition boundaries, so these rules can still inspect the meaningful branches rather than treating the wrapper as the final UI type.
Props may also contain components or component-valued Vars. Those values are part of the component relationship even when they are not positional children. This supports controls that accept render content through a prop and allows imports, hooks, and references to follow that content.
References: packages/…/component.py• L1272-1342 packages/…/component.py• L1578-1645 packages/…/component.py• L2188-2203 packages/…/tag.py• L14-31
Conditional rendering
rx.cond selects UI or a value from a condition that may be known in Python or depend on a reactive Var. When its branches are components, the result is a component tree with both branches available for frontend rendering. When its branches are values, the result is a conditional Var that can be used as a prop or text value.
An omitted false component means that the false branch renders as an empty fragment. Both branches are normalized as component content so a helper can return one component or a group of components with the same conditional interface.
The related rx.match form selects among several cases and provides a default. Component cases form a render tree. Value cases form one dynamic value, and the cases must use compatible return types.
The relationship between Python conditions, branch content, and the frontend result is shown below.
flowchart LR
C[Condition Var] --> D{Conditional render}
D -->|true| T[True component or value]
D -->|false| F[False component or value]
T --> R[Frontend expression]
F --> R
References: packages/…/cond.py• L27-118 packages/…/cond.py• L172-218 packages/…/match.py• L21-63 packages/…/cond_tag.py• L10-31 packages/…/match_tag.py• L10-31
Iteration rendering
rx.foreach creates one component for each item in an iterable Var. The render function receives the item and can also receive its index. Reflex evaluates that function with typed placeholder Vars to learn the shape, props, imports, hooks, and styles of one row. The browser then maps the same shape over the current collection.
The iterable must have a known array-like type. Object entries and split strings are normalized into iterable values. Each generated item receives an index-based key when the render function does not set one, which gives React a stable identity for list updates.
The iteration path connects a state collection to a single authored row shape and then to many frontend rows.
flowchart LR
S[State collection Var] --> I[rx.foreach]
I --> F[Typed item and index Vars]
F --> R[Row render function]
R --> M[Frontend map expression]
M --> L[Rendered component list]
References: packages/…/foreach.py• L31-122 packages/…/foreach.py• L124-180 packages/…/iter_tag.py• L19-117
Props and frontend behavior
Props define the values that a component exposes to the frontend. The component model keeps frontend props separate from compile-time metadata such as children, style collection, event chains, imports, and memoization policy.
Typed props
A component field becomes a prop when its value must reach the frontend. Its type describes the values accepted at the call site and the Var type used when the value is reactive. Literal values are lifted into Vars when needed so static and dynamic use share one render path.
Common component props provide identity and presentation:
| Prop group | Purpose |
|---|---|
key, id, ref | React identity, DOM identity, and element references |
class_name, style | CSS classes and style declarations |
custom_attrs | Extra attributes such as data-* and aria-* |
| Declared fields | Component-specific values sent to the imported or native tag |
on_* triggers | User actions and lifecycle actions connected to event handlers |
Unknown event names and values that do not match a declared Var type fail during component creation. This keeps the Python declaration aligned with the frontend component contract instead of allowing a bad prop to fail later in the browser.
Props classes provide a separate way to describe nested JavaScript objects. A props class can contain typed fields and can turn nested dictionaries or lists of dictionaries into the expected props objects before serialization.
References: packages/…/component.py• L64-161 packages/…/component.py• L776-859 packages/…/component.py• L973-1136 packages/…/props.py• L169-280
Events and lifecycle
Event triggers connect frontend actions to backend event chains. Standard triggers cover common browser actions, while component fields typed as event handlers or an overridden trigger map add component-specific actions. Mount and unmount actions are lifecycle behavior rather than ordinary tag props.
The event declaration stays attached to the component tree. Its Vars contribute dependencies and imports, and components with events request the runtime providers needed to dispatch the event to the backend. This is why a component can declare an event in Python without directly assembling the surrounding state or event-loop wrappers.
References: packages/…/component.py• L703-770 packages/…/component.py• L988-1063 packages/…/component.py• L1988-2020 packages/…/component.py• L2226-2253 tests/…/test_dynamic_components_codegen.py• L16-47
Imports and custom declarations
Component authoring declares the frontend dependencies that a UI needs without making each page manage them by hand. The compiler collects dependencies from the component itself, its Vars, its props, its children, and its custom declarations.
Import declarations
Set library and tag when a component maps to an exported frontend library value. Use alias when the emitted frontend name differs from the library export. Use is_default when the library exposes a default export. A component can add more imports with add_imports, such as a React hook or a helper from the same third-party package.
Import discovery follows the complete reachable UI tree. It includes component-valued props and Vars as well as normal children. Duplicate imports are merged, and library dependencies can be recorded separately when a component needs a package installed even if it does not emit a named import.
The public dynamic-component entry point at reflex/…/dynamic.py keeps this authoring API available while delegating its behavior to the base component package. This preserves compatibility for downstream packages that still use the older module path.
NoSSRComponent uses the same declaration model for browser-only libraries. It avoids a normal server-side tag import and exposes a client-side load instead. Use it when rendering the component on the server would be unsafe or impossible.
References: packages/…/component.py• L860-886 packages/…/component.py• L1931-1996 packages/…/component.py• L2205-2215 packages/…/component.py• L2292-2347 reflex/…/dynamic.py• L3-27
Hooks and custom code
A custom component can contribute client behavior through hooks and module-level custom code. add_hooks supplies code inside the generated React component function. add_custom_code supplies deduplicated code at module scope, after imports. These declarations are collected with the component tree so their required imports and dependencies travel with the UI that uses them.
Use the narrowest declaration that matches the behavior. A prop or Var is best for data. An event trigger is best for user action. A hook is for React runtime behavior. Module-level code is for shared client helpers or constants. The framework also adds internal hooks for refs, lifecycle events, and reactive values; custom components should extend the public add methods rather than replace those internal collection paths.
References: packages/…/component.py• L888-943 packages/…/component.py• L2072-2175 packages/…/component.py• L1824-1851
Custom UI declarations
The usual custom declaration is a Component subclass with typed fields and frontend metadata. A small declaration can map directly to a third-party tag. A larger declaration can compose other components in create, set child constraints, add imports, and expose hooks or custom code. The declaration should express the UI contract; page code should only choose its children and values.
Component namespaces support multi-part declarations when the frontend API expects a structured composition. Memoized functions support reusable declarations when a UI block should compile as a named React component. The component package ecosystem uses these same authoring rules for maintained UI libraries; see component packages for the package boundaries.
References: packages/…/component.py• L776-971 packages/…/component.py• L1280-1361 packages/…/dom.py• L24-38 packages/…/tabs.py• L19-152
Memoization
Memoization gives a component subtree a stable frontend identity so React can skip work when its relevant inputs do not change. Reflex can apply memoization during compilation, and authors can use @rx.memo when a reusable component or dynamic value should have a named compiled definition.
Memoized component functions
@rx.memo turns a typed function that returns a component into a reusable component declaration. Its parameters become props, a children parameter accepts positional component content, and an optional rx.RestProp forwards extra props. A function that returns a Var becomes a compiled JavaScript function rather than a React component.
The memo wrapper validates the function contract at the call site. It also gives the compiled result a stable name and keeps the function body separate from the page that calls it. This supports reuse and lets the compiler place the generated component in the right frontend module.
References: packages/…/memo.py• L90-178 packages/…/memo.py• L273-335 packages/…/memo.py• L1607-1730 packages/…/memo.py• L1947-2040
Memoization boundaries
The compiler uses two broad memoization shapes. A passthrough memo keeps authored descendants at the page level and passes them through a children slot. A snapshot memo owns the full internal subtree in the memo body. The distinction matters for structural components such as iteration and for components whose children are internal machinery rather than user content.
The page compiler adds memo wrappers when a component subtree carries reactive data or event callbacks. MemoizationLeaf marks a component as a boundary when its descendants must stay together. Foreach uses the same non-recursive policy because its row render logic belongs inside the iteration unit. Event handlers can also receive stable callback wrappers so unchanged subtrees keep stable handler identities.
Boundary wrappers keep state reads and hooks inside the generated component that owns the subtree. The compiler builds these wrappers for each compile from the source module context, so the generated component remains connected to the page's imports and application providers without relying on one shared stateful-components module.
References: packages/…/memoize_helpers.py• L1-18 packages/…/memoize_helpers.py• L38-43 packages/…/memoize_helpers.py• L91-148 packages/…/memoize_helpers.py• L180-214 packages/…/component.py• L2350-2365 packages/…/foreach.py• L31-35 reflex/…/memoize.py• L1-19 reflex/…/memoize.py• L130-204 reflex/…/memoize.py• L206-227 reflex/…/memoize.py• L359-407
Rendering contract
Rendering converts the component tree into a neutral tag description that the frontend compiler can turn into JSX. The description preserves the tag name, formatted props, children, conditional branches, iteration metadata, and dynamic values. It also provides the source from which the compiler gathers imports, hooks, custom code, refs, and app wrappers.
The normal render path follows this sequence:
- Component creation validates children, props, event triggers, and style inputs.
- The component chooses its tag and gathers frontend-facing props.
- Children and component-valued props render into nested descriptions.
- Conditional and iteration components retain their special render form.
- The compiler adds memo boundaries where reactive data or callback identity requires them.
- The compiler collects the reachable dependencies and emits the frontend code.
The render result is cached for an unchanged component instance. Compile-time copies clear that cache when the compiler changes a component tree, which keeps the rendered result aligned with the current declaration.
flowchart TD
P[Python component declaration] --> V[Validate props and children]
V --> T[Build tag description]
T --> C[Render child and dynamic branches]
C --> M[Add required memo boundaries]
M --> D[Collect imports, hooks, refs, and app wraps]
D --> J[Frontend JSX and runtime expressions]
References: packages/…/component.py• L1194-1240 packages/…/component.py• L1293-1361 packages/…/component.py• L1478-1496 packages/…/component.py• L1979-1996 packages/…/tag.py• L50-105 reflex/…/memoize.py• L229-357
Related systems
Component authoring depends on the systems that give Vars their reactive meaning and turn declarations into frontend files. Read reactive variables and dependency tracking for dynamic values and dependencies. Read styling and theming for style declarations and theme behavior. Read frontend compilation for the later stages that assemble imports, pages, and build output.
Change checklist
When these files or sections are changed, remember to consider these:
- A change to component field annotations can alter both call-site validation and the emitted JavaScript prop type. Check component declarations and any matching package documentation together.
- A change to
library,tag,alias, oris_defaultmust keep import names, generated component names, and dynamic import behavior aligned. - A change to the public dynamic-component entry point must preserve the compatibility path used by downstream packages and the active library registration context.
- A new
on_*field or trigger must preserve its argument contract so event chains and generated frontend handlers agree. - A component-valued prop must remain visible to dependency, hook, ref, and app-wrap collection. Otherwise nested UI can render without its required frontend support.
- A change to iteration or conditional branch shape must preserve the special tag form and the component rules that inspect those branches.
- A change to memoization rules must preserve the placement of structural children, reactive hooks, event callbacks, app wrappers, and refs across page and memo modules.
- A change to automatic memo wrapper generation must keep wrappers tied to the source module and compile context so imports and state-backed handlers remain available in the generated frontend.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A reactive prop receives a value outside its declared Var type | Component creation raises a type error before frontend compilation | Declare the correct Var type and use a Var conversion when the expression needs one |
An on_* name is not in the component trigger contract | The component rejects the event instead of generating a handler | Add the event trigger with the correct argument specification |
rx.foreach receives an untyped or non-array-like Var | Reflex cannot infer the row item type or build the frontend map | Add a concrete collection annotation and pass a render function with one or two parameters |
A memo function receives an undeclared prop without rx.RestProp | The call fails and the value is not silently forwarded | Declare the prop or add an rx.RestProp parameter |
| A browser-only library is authored as a normal server-rendered component | Server rendering can load a client-only dependency | Use NoSSRComponent for the browser-only declaration |
| A component replaces internal hook or dependency collection instead of extending it | Refs, lifecycle actions, imports, or event providers can disappear from generated output | Use add_imports, add_hooks, and add_custom_code and keep framework collection methods intact |
| A reactive subtree is placed outside its compiler memo boundary | State reads or callback hooks can leak into page-level output and cause extra renders or invalid hook placement | Preserve the boundary strategy and let the compiler wrap the owning subtree |
| An auto-generated memo wrapper loses the original subtree's app wrappers or refs | Providers or form actions can no longer reach content inside the memoized component | Keep app-wrapper and ref collection connected to the original component when the wrapper replaces it |
Key files
| File | Why to read it |
|---|---|
| packages/…/component.py | Defines the component fields, creation contract, tag mapping, render result, dependency collection, and component-valued relationships. |
| packages/…/tag.py | Shows the neutral tag shape used to carry props and children toward frontend rendering. |
| packages/…/cond.py | Defines conditional component and value rendering. |
| packages/…/foreach.py | Defines typed iteration rendering and row identity behavior. |
| packages/…/memo.py | Defines authored memo functions and the component wrappers they produce. |
| packages/…/memoize_helpers.py | Explains memoization strategies and stable event callback behavior. |
| reflex/…/memoize.py | Applies automatic memo boundaries during page compilation and keeps wrapped state, callbacks, app wrappers, and refs connected to generated components. |
| packages/…/props.py | Defines typed nested prop objects for JavaScript-facing component values. |
| reflex/…/dynamic.py | Provides the public compatibility entry point for dynamic component authoring and library registration helpers. |
| packages/…/element.py | Defines the base mapping for native HTML and SVG elements. |
| packages/…/fragment.py | Shows the tag-backed fragment used for container-free composition. |
| tests/…/test_dynamic_components_codegen.py | Demonstrates that dynamic component trees retain state-backed event handlers in generated frontend code. |