Introducing a new way to review your PRs.

Read the announcement

reflex-dev / reflex

🕸️ Web apps in pure Python 🐍

View on GitHub

30 documents · Updated Nov 23, 2026

docs / reactive-vars

Reactive variables and dependency tracking

Reactive variables, or Var values, let Python declarations describe values that the browser evaluates later. They preserve type information, carry the state links needed by the rendered UI, and connect state changes to the expressions that must update. This page is a child of Reactive values and styling and relates to Styling and theming and State and events.

Var model

Expression identity

The Var model represents an immutable frontend expression rather than a value that Python can read at declaration time. Each var has a JavaScript expression, a Python type for checks and editor support, and metadata for state reads, imports, hooks, and related components. A literal becomes a literal var. A state field becomes a state-bound var.

This model lets one expression move through component props, conditions, loops, and styles without losing its source state. Operations create new vars, so composing an expression does not change the vars that supplied it. A composed var keeps the state fields used by all of its inputs, which lets later dependency checks track every source field.

References: packages/…/base.py• L332-541 packages/…/base.py• L723-906 packages/…/base.py• L924-965

State-bound values

State class attributes expose typed vars for frontend use. State setup gives each public field a stable state and field identity. Class access builds a frontend expression. Instance access reads or changes the Python value at runtime. This gives component declarations and event handlers two views of the same state.

Direct field reads carry the field name into the frontend state subscription, so a component can keep its prior state view when other fields change. An expression that can read any key of a substate subscribes to the whole substate instead. This keeps narrow readers efficient without treating a dynamic state expression as one named field.

The built-in router value is a composite state view. Class access returns a typed var over route-related fields. Instance access combines those fields into one router value, while assignment splits a router value back into its fields. Incoming router data is merged with the last router view, so a partial navigation update does not clear connection data that the update does not contain. Only fields fed by changed router inputs are rebuilt. This keeps connection data separate from navigation data when the system builds an update.

State code can also resolve a state-bound var to its current value. A literal resolves directly. An operation resolves through its original state-bound inputs, including a value held by another state in the same client state tree. This is the runtime bridge between an expression passed to server code and the state value that it names.

References: packages/…/base.py• L618-651 packages/…/base.py• L1380-1408 reflex/state.py• L259-278 reflex/state.py• L412-477 reflex/state.py• L1552-1634 reflex/state.py• L1805-1858

Function expressions

FunctionVar represents a callable frontend expression. It supports calls and partial application with either literal values or other vars. The result is another typed expression, so a callback can read current state when the browser invokes it rather than capture a Python value from declaration time.

Function calls preserve the metadata of the function and its arguments. This keeps state reads inside callbacks connected to the expression that uses them. Nullable callable vars use an optional call, so a missing callback becomes a no-op instead of a client-side call error.

References: packages/…/function.py• L126-276 packages/…/function.py• L334-416 packages/…/base.py• L471-541

Client-side values

ClientStateVar represents a typed value that lives in the browser through React state. It gives components a reactive value expression and frontend event actions for setting that value. A global client state var also exposes the value to backend event handlers through retrieval and accepts backend-triggered updates through push events.

The var is placed on the highest shared component scope that needs it. Its shared reference lets sibling components use the same client value, while a local var stays inside its component scope. This state path is separate from server state, so backend access requires an explicit event boundary.

References: reflex/…/client_state.py• L57-71 reflex/…/client_state.py• L86-193 reflex/…/client_state.py• L195-249 reflex/…/client_state.py• L264-301

Typed value families

Type families

The var system selects a specialized family from the Python type. Each family provides operations that match the value and keeps the result useful for later checks and expressions. The main families are:

FamilyValuesTypical result
NumberVar and BooleanVarNumbers and booleansArithmetic, comparison, and boolean expressions
StringVarStringsText changes, search, split, and comparison
ArrayVarLists and tuplesIndexing, slicing, filtering, mapping, and length
SetVarSets and frozen setsMembership, set algebra, and set comparisons
ObjectVarMappings and serializable structured objectsField access, key access, entries, values, and merge
FunctionVarCallable frontend expressionsCalls, partial application, and callback expressions
DateTimeVar and ColorVarDates, datetimes, and colorsDate comparison and theme-aware color values

Var.create, Var.to, and Var.guess_type provide the conversion points when a value enters an expression or needs a more specific type. Structured values can retain declared element and field types, including values from dataclasses and supported models.

References: packages/…/base.py• L765-812 packages/…/base.py• L967-1307 packages/…/function.py• L126-127 packages/…/number.py• L61-62 packages/…/sequence.py• L66-67 packages/…/set.py• L175-176 packages/…/object.py• L77-85 packages/…/datetime.py• L43-44 packages/…/color.py• L18-19

Primitive operations

Primitive vars turn familiar Python expressions into browser expressions. Numeric operators return numeric vars. Comparisons return boolean vars. String methods return string or boolean vars. Literal operands become literal vars so a state-bound value can combine with a normal Python value.

The result remains an expression. The system does not calculate it in Python when the component is declared. The browser can therefore use the latest state value after an update. Boolean composition uses var operations instead of Python truth evaluation, so the expression keeps its reactive inputs.

References: packages/…/number.py• L61-115 packages/…/number.py• L362-438 packages/…/sequence.py• L783-1005 packages/…/base.py• L1401-1529 packages/…/base.py• L2467-2530

Structured operations

Structured vars make nested data usable in a UI without first copying it into separate fields. Array access returns a var for an element. Array methods build expressions for common collection work. Object access uses the declared field or value type, so a nested object can continue through the same operation system.

Sets form a separate family because their frontend value is transported as an array while their operations keep set semantics. Membership and set algebra remain set operations. Use to_array() before indexing, ordering, mapping, filtering, or other sequence work. Direct array-style operations on a set are retained only as deprecated compatibility paths.

The system also supports operations that shape structured data for components. These include object key and value views, object merging, array mapping and filtering, and safe access for missing values. A plain Python loop or membership test is not the frontend expression form. Use the var operations designed for those cases.

References: packages/…/sequence.py• L66-77 packages/…/sequence.py• L226-355 packages/…/sequence.py• L467-633 packages/…/set.py• L1-8 packages/…/set.py• L175-342 packages/…/object.py• L111-170 packages/…/object.py• L225-265 packages/…/object.py• L545-609

Computed dependencies

Computed vars

A computed var is a typed state value produced by a getter instead of stored as a normal field. rx.var defines derived values that the UI can read. The getter must declare its return type. It can run synchronously or asynchronously.

Cached computed vars recalculate when their inputs change. A computed var can also use an initial value, a refresh interval, explicit dependencies, or a server-only setting. A non-cached computed var recalculates for each state delta. The update path can omit it when its value matches the last value delivered to that client.

References: packages/…/base.py• L2619-2729 packages/…/base.py• L2739-2829 packages/…/base.py• L2898-3043 reflex/state.py• L930-978 reflex/state.py• L1031-1039

Dependency discovery

Dependency discovery records which state fields a cached computed getter may read. The tracker follows direct field access, helper methods, properties, nested functions, comprehensions, and reads from another state obtained through get_state. It records every possible branch of a conditional because a later state change can select a different branch.

The computed var combines automatic discovery with explicit dependencies. Use explicit names or state-bound vars when the getter uses a pattern the tracker cannot identify. Set auto_deps=False only when the explicit list is complete. An omitted dependency can leave a cached value stale. The composite router view resolves to its per-field state sources, so a dependency can target one router field or all router fields.

References: packages/…/base.py• L2739-2794 packages/…/dep_tracking.py• L80-118 packages/…/dep_tracking.py• L149-217 reflex/state.py• L1031-1039 reflex/state.py• L1785-1803 reflex/state.py• L1805-1858

Expression leaves

Expression leaf tracking finds the source vars that a rendered operation reads. It unwraps composed operations, casts, literal containers, and function bodies. A function body contributes the vars it reads outside its own parameters. This gives frontend hooks the real reactive inputs instead of treating every newly built operation as an unrelated value.

The tracker keeps a function whole when a nested leaf still depends on one of the function's parameters. That prevents a source that only exists inside a callback or collection operation from being moved outside its valid scope. This expression-level tracking complements state-field metadata: the former supports frontend expression dependencies, while the latter drives state invalidation.

References: packages/…/base.py• L3715-3834 packages/…/function.py• L483-589 packages/…/base.py• L332-541

Cache invalidation

State classes turn computed dependencies into a reverse lookup from a changed field to the computed vars that depend on it. When a base field becomes dirty, the state walks that lookup, clears affected cached values, and marks dependent computed vars dirty. The walk continues through computed-var chains and across state branches.

For the composite router value, the reverse lookup uses the underlying router fields. A change to navigation data can refresh dependent expressions without treating connection-static data as changed. Partial router input carries forward omitted values before the state compares and rebuilds the affected fields. Cached values are selected for the next delta by this dependency graph. Non-cached values recalculate for each delta, while delivery tracking uses the serialized value sent to each client so an unchanged value is not sent again.

References: reflex/state.py• L1552-1634 reflex/state.py• L1860-1901 reflex/state.py• L1903-1917 packages/…/base.py• L2564-2589 packages/…/base.py• L2858-2897

Expression boundaries

Literal conversion

Literal conversion is the entry point for Python values used in expressions. Basic values become literal vars. Lists, mappings, sets, and supported structured values become typed array, set, or object vars. A value that exposes a var form can provide its own expression. Otherwise the value must be supported by the serializer registry or by the built-in structured-value rules.

The conversion keeps nested var metadata. For example, a literal collection that contains state-bound values still carries the dependencies and imports of those values into the final expression.

References: packages/…/base.py• L967-1089 packages/…/base.py• L1830-1976 packages/…/base.py• L2210-2246 packages/…/sequence.py• L659-753 packages/…/set.py• L743-825 packages/…/object.py• L487-500

Serializer registry

The serializer registry converts Python values that do not have a direct primitive form into JSON-friendly values or strings. It supports common values such as mappings, sequences, dates, enums, UUIDs, paths, decimals, colors, and optional integrations. An application can register a serializer with rx.serializer. The function takes one value and returns the representation that the frontend can use.

The declared output type matters. A serializer that returns a string makes the value behave as a string var. A mapping result can become an object var. If no serializer exists, the value cannot safely enter a literal expression.

References: packages/…/serializers.py• L27-35 packages/…/serializers.py• L67-134 packages/…/serializers.py• L151-181 packages/…/serializers.py• L248-262 packages/…/serializers.py• L265-408

JSON forms

Literal vars provide JSON forms for values that must appear directly in a generated expression. Literal arrays, sets, and objects require literal children for this form. Sets are ordered for literal rendering, then travel to the frontend as JSON arrays. A state-dependent child is an expression and cannot be reduced to one fixed JSON value. Numbers also reject non-JSON values such as NaN and infinity.

State values use a separate transport path. A state delta selects dirty public fields and frontend computed vars. Server persistence serializes state instances with a state schema. The delta path tracks values that were delivered to a client. The persistence path omits parent and child links that the state manager restores separately.

References: packages/…/object.py• L442-459 packages/…/sequence.py• L670-687 packages/…/set.py• L728-801 packages/…/number.py• L1000-1019 reflex/state.py• L1919-1935 reflex/state.py• L1991-2042 reflex/state.py• L2064-2084 reflex/state.py• L2131-2206

State update flow

Expression-to-update path

An expression begins as a class-level state read and ends as a client update after an event changes the source state. The state layer uses the dependency graph to add affected computed values to the delta before the client receives it. Expression leaf tracking separately supplies the direct frontend inputs needed by generated hooks and callbacks. Direct state-field readers subscribe to the fields they name, so unrelated field changes do not force those readers to refresh. Expressions that can read an entire substate keep a whole-substate subscription.

Router state follows the same path through separate source fields. Partial router input merges with the last router view before comparison. Connection-scoped values remain in place when navigation input omits them. A change to the origin can affect the URL and page data, while other header changes do not rebuild navigation values. Only fields affected by changed connection or navigation data are rebuilt, so a navigation update does not resend stable session or header values. Client-side values use a parallel browser-local path: their value expression reads the local state, while set, retrieve, and push cross the frontend or backend event boundary.

The diagram shows how declaration, runtime evaluation, and the update boundary relate.

flowchart LR
    A[State field or computed getter] --> B[Typed Var expression]
    B --> C[Component prop, condition, loop, or style]
    C --> D[Generated frontend expression]
    E[Event handler] --> F[State field change]
    F --> G[Dirty field]
    G --> H[Dependent computed vars invalidated]
    H --> I[State delta]
    I --> J[Frontend state context]
    J --> D
    D --> K[Field or whole-substate subscription]
    K --> D
    L[ClientStateVar] --> M[Browser-local value]
    M --> D
    D --> N[Frontend event]
    N --> L
    N --> E

State changes mark the changed field and its state branch as dirty. Before a delta is built, the state marks expired, always-dirty, and dependency-linked computed vars. The delta then contains the public values needed by the frontend. Backend-only values remain on the server. A non-cached computed value counts as delivered only after the resolved delta still contains it, so later deltas can retry values that an outer delta hook removed.

Page load handlers are queued without copying router metadata into generated frontend events. Backend event context keeps the request view for server-side handling, while the frontend event does not need routing data that could expose server-only request details.

References: packages/…/base.py• L618-651 packages/…/base.py• L1380-1408 reflex/state.py• L1552-1634 reflex/state.py• L1860-1957 reflex/state.py• L1919-1935 reflex/state.py• L2608-2632 reflex/…/client_state.py• L195-301 packages/…/base.py• L488-540 packages/…/base.py• L3715-3834

Frontend-backend properties

hybrid_property supports one conceptual value on both sides of the boundary. Instance access runs the normal Python getter. State-class or object-var access builds a frontend var from that getter or from a separate .var function. A frontend form must not read a backend-only state field.

This feature is useful for derived object fields because it keeps the backend value and the frontend expression aligned. It does not make server-only data safe to expose. The guard rejects such reads while the frontend expression is built.

References: packages/…/hybrid_property.py• L12-18 packages/…/hybrid_property.py• L56-121 packages/…/hybrid_property.py• L123-138 tests/…/test_hybrid_property.py• L11-59 tests/…/test_object.py• L178-194

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Python type returned by a var operation aligned with the value produced by its frontend expression. This affects Var.guess_type, typed component props, and nested object, array, or set access.
  • When changing state var hook metadata, keep named field subscriptions aligned with the field metadata and with whole-substate expressions. A malformed or overly broad subscription can cause duplicate state hooks or unnecessary reader refreshes.
  • When changing computed getter rules, update both dependency discovery and the reverse dirty lookup. A getter can be correct at runtime but still leave a cached frontend value stale if its dependency is not recorded.
  • When changing function vars or callback expressions, keep argument conversion, callable result types, nullable calls, and expression-leaf tracking aligned. A callback can render correctly but use the wrong hook dependency scope.
  • When changing the composite router value, keep class-level var access, instance-level assembly, partial-input merging, input-specific rebuild rules, and per-field dependency expansion aligned. A mismatch can refresh too much state or leave a router-based computed value stale.
  • When adding a serializable Python type, define its serializer output type and check how LiteralVar.create maps that output to a string, object, collection, or primitive var.
  • When changing set behavior, keep the JSON-array transport form, set semantics, result type, and to_array() boundary aligned. Array-style compatibility methods must retain their deprecation path until the public contract removes them.
  • When changing client-side state, keep the component hook scope, shared refs, frontend setter, and backend event bridge aligned. A mismatch can create a private state copy or make a backend access path unavailable.
  • When changing state delta selection, keep backend-only vars out of the client payload. Keep serialized delivery keys aligned with any code that drops or replaces delta entries.
  • When changing state persistence, keep the state schema in step with the fields included in the serialized state. Parent links and substates must remain reconstructable without being stored inside each state object.
  • When changing page-load event creation, keep request metadata in backend event context and out of generated frontend event payloads. Client routing data must not become a second path for server-only request values.
  • When changing a hybrid property, check both instance evaluation and class-level var construction. A custom .var form must not expose backend-only state fields.
  • When adding a Var family or conversion target, register it with the type dispatch used by Var.to and Var.guess_type. Stale or missing registration changes the type of later expressions.

Important failure modes

TriggerConsequenceGuard
A Var is used with Python if, and, or, not, direct iteration, or inPython tries to evaluate or iterate a browser expression before the browser has a valueUse rx.cond, bitwise &, `
A state hook uses an expression as a named field when the expression can read the whole substateThe frontend can build an invalid field subscription or duplicate state declaration instead of sharing one state contextUse a whole-substate subscription for dynamic state expressions and a field subscription only for a real field name
A callback function expression captures a parameter-dependent leaf as if it were a free state valueThe generated dependency list can name a value outside the callback's scopeKeep the function expression scoped; the leaf tracker retains the function when its leaf depends on a bound parameter
A SetVar is indexed, mapped, filtered, or treated as an ordered arrayThe code uses a sequence operation on a value whose contract is set membership and set algebraCall to_array() before sequence operations
A set is passed to an operation that expects a sequence without crossing the array boundaryThe operation raises a type error or follows a deprecated compatibility pathUse a set operation or call to_array() explicitly
A ClientStateVar is local but a backend event calls retrieve or pushThe event cannot access the browser-local valueCreate the var with global access when a backend event must read or update it
A global client var is rendered without the shared owner component in scopeThe reader or setter can use an absent or wrong state slotInclude the client state var in the highest parent shared by its users
A computed getter has no return annotation or has the wrong return valueThe computed value cannot get a reliable frontend type, or the state logs a type mismatchAdd a concrete return annotation and return that type
Automatic dependency discovery cannot resolve a state class or local referenceA cached computed var may not refresh for a dependency, or discovery emits a warningUse state-bound explicit deps and set auto_deps=False only with a complete list
A computed var uses the deprecated string dependency deps=["router"]The dependency expands to all router fields and emits a deprecation warningUse State.router for all router fields or State.router.url for one field
A partial router update omits a value needed to build a later router viewMissing connection or origin data can clear or corrupt router-derived valuesMerge the new router input with the last router data before rebuilding dependent fields
A literal array, set, or object contains a non-literal child when JSON form is requiredThe value cannot be reduced to a fixed JSON expressionKeep it as a reactive expression or serialize a fully known value
A Python value has no registered serializer or supported literal formVar creation raises an unsupported-type errorRegister rx.serializer with a JSON-friendly return type
A generated page-load event is given router metadata for frontend transportServer-only request data can enter a client event payloadBuild load events without router data and use the backend event context for request state
A hybrid property reads a backend-only state fieldFrontend var construction raises a HybridPropertyError instead of exposing server dataUse a public field or provide a separate frontend .var implementation
A state subclass redeclares an inherited var with a stored fieldClass setup rejects the shadowing definition and the intended reactive field is not unambiguousKeep the inherited var or choose a new field name
An operation receives an unsupported operand type or an untyped Var is indexed or accessedVar construction raises a type or attribute errorCorrect the state annotation and use an operation supported by the var family
Persisted state has a different field schema from the running state classState restore raises a schema mismatch instead of loading an incompatible valueTreat state field type and default changes as persistence contract changes

Key files

FileWhy to read it
packages/…/__init__.pyShows the public Var families and conversion helpers exposed by the var package.
packages/…/base.pyDefines the common var model, metadata, type conversion, computed vars, expression leaves, delta comparison, state subscriptions, and operation construction.
packages/…/function.pyShows callable frontend expressions, partial application, function calls, and callback expression scope.
packages/…/number.pyShows typed arithmetic, comparisons, booleans, and literal number rules.
packages/…/sequence.pyShows string and array expressions, including collection transforms.
packages/…/set.pyShows set transport, set algebra, membership, and the boundary between set and array operations.
packages/…/object.pyShows typed field access and operations over mappings and structured values.
packages/…/dep_tracking.pyDefines the dependency model for computed getters and cross-state reads.
packages/…/serializers.pyDefines built-in and application-provided conversion to frontend-safe values.
packages/…/hybrid_property.pyDefines the shared backend and frontend property boundary.
reflex/…/client_state.pyDefines browser-local typed state and its frontend and backend event bridges.
reflex/state.pyConnects state fields, the composite router view, computed vars, dirty tracking, client deltas, runtime var lookup, page-load events, and state persistence.
tests/…/test_dep_tracking_integration.pyDemonstrates the dependency contract for simple, nested, conditional, and cross-state computed values.
tests/…/test_serializers.pyDemonstrates the serializer contract across primitive, structured, enum, date, and custom values.