State management and event processing
Reflex keeps each application session in a server-side state tree and uses events to move changes between the browser and the server. State fields and computed values describe the view, event handlers change the model, and state managers keep the model available while updates are processed. This page supports the broader application runtime; see application lifecycle, frontend compilation, frontend runtime package, routing and pages, and runtime foundations for related views.
State tree
The state tree is the session model for an application. A root state owns child states, and each child owns the values and handlers for one part of the application. This structure gives handlers one session view while keeping ownership clear between pages, shared features, and component instances.
flowchart TD
Root[Root state] --> Page[Page or feature state]
Root --> Shared[Shared or internal state]
Page --> Component[Component state]
StateVars[Declared state values] --> Root
StateVars --> Page
Derived[Computed values] -. depend on .-> StateVars
State values
A state class declares values that the browser may render and values that remain on the server. Computed values derive from other state values, so the runtime can refresh them when their inputs change. Component state gives a reusable UI part an independent state scope.
The browser receives only frontend-visible values. Backend-only values can support handler work and safe computed values without becoming client state.
References: reflex/state.py• L623-671 reflex/state.py• L841-914 reflex/state.py• L1184-1255 reflex/state.py• L3131-3168
State identity
A state token identifies the session that owns a state tree. It also identifies the state class or state part that an event needs. This identity lets the runtime load the right tree and lets a shared state use a separate identity when several clients must see the same values.
The manager interface uses typed tokens. Older string forms are converted at the boundary so storage and event code can use one identity model.
References: reflex/state.py• L1310-1362 reflex/…/token.py• L17-67 reflex/…/token.py• L122-171 reflex/…/__init__.py• L99-114
Router context
Router context is the part of the state tree that describes the connection and the current page. It gives handlers and computed values access to session data, safe request headers, the current URL, and the matched route.
State.router presents this information as one view while the runtime keeps connection data separate from navigation data. Partial route changes can therefore update page values without resending unchanged connection values. Private cookies and credential headers stay on the server side.
References: reflex/state.py• L419-484 reflex/state.py• L689-719 reflex/state.py• L1703-1785
State mutations
State mutations are the changes that an event makes to the session model. The runtime records direct assignments and in-place changes to mutable values, then turns the recorded work into a delta for the browser.
Mutation tracking
Each state records changed values and changed child states. A change in a child marks its ancestors, which lets the runtime find the smallest useful part of the tree to send. Mutable values use tracked views so list, dictionary, set, dataclass, and supported model changes follow the same path as assignment.
Computed-value dependencies extend this path. When an input changes, dependent computed values become eligible for refresh, including dependents in another state. Backend-only values affect this work but do not appear in the client delta.
References: reflex/state.py• L663-687 reflex/state.py• L2011-2062 reflex/state.py• L2100-2133 reflex/…/proxy.py• L611-822 reflex/…/proxy.py• L839-1106
State delta
A state delta is the set of frontend-visible values that changed during an event. The runtime resolves values that need asynchronous work before it delivers the delta, and it clears change markers after it captures a full state or sends an update.
The delivered update has two parts:
deltacontains changed state values.eventscontains follow-up browser or server events.
The runtime delivers the delta before the follow-up events. A later event therefore starts with the newest client view.
References: reflex/state.py• L2080-2099 reflex/state.py• L3243-3289 reflex/…/delta.py• L214-308
Event handlers
An event handler is an application action that runs after a user action or another system event. The framework turns eligible state methods into event targets and uses the target state class to apply the event to the correct part of the tree.
Handler contracts
Handlers can be regular functions, async functions, or generators. They can return or yield more events, which creates a chain. The runtime validates those events and sends browser actions to the client while placing server events back on the event queue.
Event payloads are matched to handler type hints when possible. This lets common values such as models, enums, collections, and dates cross the browser-to-server boundary in a form the handler can use.
References: reflex/state.py• L1507-1551 reflex/state.py• L853-906 packages/…/base_state_processor.py• L45-170 packages/…/base_state_processor.py• L231-293
Handler discovery
Handler discovery decides which state methods can enter event dispatch. By default, every public method on a user-defined state becomes an event handler. With state_explicit_event_handlers enabled, only methods decorated with @rx.event become handlers, while other public methods remain ordinary Python methods.
This mode lets a state class keep local helper methods without exposing them as browser event targets. If a plain method is wired to a trigger or returned as an event, the runtime rejects it and points to the missing @rx.event decorator. The same rule applies when handlers come from state mixins.
References: reflex/state.py• L567-621 reflex/state.py• L854-907 reflex/state.py• L955-999 packages/…/config.py• L190-196 packages/…/config.py• L279-284
Background handlers
Normal handlers run while the session state is locked. This prevents two ordinary events for one session from changing the same model at the same time. Background handlers run outside that lock, so long work does not block later events.
When background work must change state, it enters a short async state context. The context refreshes the current state, applies the change under the session lock, captures the delta, and releases the lock. This separates long work from the small section that changes shared data.
References: reflex/state.py• L2216-2231 reflex/…/proxy.py• L153-176 reflex/…/proxy.py• L228-309 packages/…/base_state_processor.py• L382-404
Event dispatch
Event dispatch connects browser actions to server handlers and returns state updates to the browser. The browser queues events, and the server uses the session token to find the state tree that must process each event.
Client dispatch
The generated client sends events that need server state through the live socket. Events with names that start with _ represent browser actions such as navigation, focus changes, storage changes, and script calls. File upload uses a separate client path.
The client adds current route data when a server event needs it. This keeps handler input aligned with the page that caused the event while keeping private request data out of the browser payload.
References: packages/…/state.js• L148-157 packages/…/state.js• L220-431 packages/…/state.js• L440-462 packages/…/state.js• L501-559
Server dispatch
The server places incoming events in an async queue. It resolves the handler, loads the state for the event token, runs the handler, saves changes, and returns a state update.
The normal queue preserves order for one session token. Events for different tokens can run at the same time. Background events use a separate path so long work does not hold the normal state lock.
sequenceDiagram
participant Browser
participant Queue as Event queue
participant Processor as Server processor
participant Manager as State manager
participant Handler as State handler
Browser->>Queue: Queue event
Queue->>Processor: Send event and token
Processor->>Manager: Load and lock state
Manager-->>Processor: Current state
Processor->>Handler: Run handler
Handler-->>Processor: Mutations and follow-up events
Processor->>Manager: Persist changed state
Processor-->>Browser: Delta and follow-up events
Browser->>Browser: Apply delta and render
References: packages/…/event_processor.py• L83-137 packages/…/event_processor.py• L374-415 packages/…/event_processor.py• L609-697 packages/…/base_state_processor.py• L331-404
Event ordering
The per-token queue stops ordinary handlers for one session from changing shared state at the same time. A chained event keeps the source event context, so it uses the same session and route data. Cancellation removes queued work and its child events in the same chain.
References: packages/…/event_processor.py• L401-415 packages/…/event_processor.py• L495-535 packages/…/event_processor.py• L625-653 packages/…/event_processor.py• L714-775
Hydration
Hydration is the first synchronization step between a rendered page and its server state. When the browser connects, it sends a hydrate event. The server returns a state snapshot, applies browser storage values, and runs page-load work before the root state becomes hydrated.
Initial hydration
Hydration resets client-storage fields on the server before applying values sent by the browser. If the browser has the same compiled defaults as the server, the runtime sends only values that differ. Otherwise it sends the full snapshot. It then sends storage corrections and clears change markers so the browser and server share the same starting view.
The browser holds events that need hydrated state until it receives the hydrated marker. The runtime keeps page-load work in a separate follow-up event so a newer navigation can cancel stale work without losing the current snapshot.
flowchart LR
Connect[Socket connection] --> Hydrate[Hydrate event]
Hydrate --> Reset[Reset client-storage values]
Reset --> Apply[Apply browser storage]
Apply --> Snapshot[Full or default-diff snapshot]
Snapshot --> Corrections[Storage corrections]
Corrections --> Load[Page load events]
Load --> Ready[Hydrated marker]
Ready --> Render[Apply state and render]
References: reflex/state.py• L2658-2749 reflex/state.py• L2794-2926 packages/…/state.js• L672-786
Navigation hydration
A route change marks the root state as not hydrated and queues the new page's load work. A newer navigation supersedes unfinished load work for the same client token, so old page setup does not continue after the user changes route.
References: reflex/state.py• L2953-2977 reflex/state.py• L3099-3129 packages/…/state.js• L1170-1208 packages/…/base_state_processor.py• L343-387
State backends
The state manager is the storage and lock boundary for session state. The event processor uses one manager contract while an application chooses where state lives, so the same event flow can work in one process or across several processes.
Manager contract
The manager loads state for a token, stores it after a change, and provides an exclusive modification context. Ordinary event processing uses that context around state mutations. Linked state extends it so all affected state owners can be locked and updated together.
The selected backend can keep state in process memory, on the local host, or in Redis. Typed state tokens identify both the session and the state part used by the manager.
References: reflex/…/__init__.py• L27-35 reflex/…/__init__.py• L60-114 reflex/…/__init__.py• L170-230 reflex/…/token.py• L17-119
Backend modes
The backends trade simplicity for persistence and process sharing:
| Backend | State location | Main role |
|---|---|---|
| Memory | Process memory | Fast local use in one process. State ends with the process. |
| Disk | Local state files with a process cache | Host-local persistence across restarts. Writes can be delayed. |
| Redis | Redis with session locks and serialized state | Shared state for several backend processes. |
All backends use tokens and exclusive modification contexts. Persisted state carries a schema marker, so state that no longer matches the current model can be rejected instead of loaded as an unsafe object. Memory expires inactive state in the process. Disk removes expired files. Redis uses key expiry and locks across processes.
References: reflex/…/__init__.py• L36-97 reflex/…/memory.py• L20-108 reflex/…/disk.py• L65-145 reflex/…/redis.py• L318-409 reflex/…/redis.py• L411-516 reflex/state.py• L2303-2434
Disk persistence
The disk backend restores a state tree from host-local state files and keeps active trees in a process cache. It marks a replacement tree as changed so a state object supplied from outside the cache is also written. Deferred writes reduce file activity, while shutdown flushes pending writes before the manager closes.
The backend removes expired files and inactive cached sessions. It does not purge a token while its state lock is held or while a write remains pending.
References: reflex/…/disk.py• L42-65 reflex/…/disk.py• L131-174 reflex/…/disk.py• L208-280 reflex/…/disk.py• L358-420 reflex/…/disk.py• L433-507
Shared state
Shared state links a state part to one token so several clients can observe the same values. The runtime locks the linked state, applies it to the active client tree while the event runs, and creates updates for other connected clients after a change.
Shared state is a synchronization feature, not a replacement for private session state. Sensitive values should remain backend-only, while each client receives only its safe view.
References: reflex/state.py• L2631-2656 reflex/…/shared.py• L40-81 reflex/…/shared.py• L84-192 reflex/…/shared.py• L226-302 reflex/…/shared.py• L312-380 reflex/…/__init__.py• L214-333
Change checklist
When these files or sections are changed, remember to consider these:
- State names, frontend-visible values, or handler names change the generated browser state schema and dispatch map. Keep the compiled frontend and backend schema aligned.
- Explicit handler mode changes which public state methods can be dispatched. Keep
state_explicit_event_handlers,@rx.eventusage, mixin methods, and trigger wiring aligned. - State field types and defaults affect both persisted state compatibility and the initial browser snapshot. Account for existing disk or Redis sessions.
- Computed-value dependencies affect which state parts become dirty. Review source values and all computed values that depend on them.
- Delta changes must keep delivery tracking tied to the update that reaches the browser. A discarded delta must not make the server think the browser received it.
- Hydration changes must keep browser storage input, the initial snapshot, storage corrections, and the hydrated marker in the same order.
- Router data keys and frontend router fields must stay aligned. Partial route data must preserve connection values that were not included.
- A change from normal to background handling changes the lock and write contract. Keep background writes inside the short async state context.
- Disk debounce and close changes must preserve pending-write flushes and replacement-tree persistence.
- Shared-state link changes must preserve updates for connected clients and full rehydration for the client that changes its link.
- Navigation load changes must preserve supersession so an old route cannot run setup after a newer route.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Browser and backend state schemas differ | Unknown state parts are skipped and the backend receives a client error. | Rebuild the frontend when state names, values, or handlers change. |
| Explicit handler mode is enabled but a public helper is wired to a trigger | The event cannot be built because the method is not an event handler. | Add @rx.event to methods meant for dispatch, or keep helpers out of event triggers. |
| A long normal handler holds the session lock | Later events wait. A Redis write can fail if the lock expires. | Move long work to a background handler and keep state writes short. |
| Background code writes outside its async state context | The write is rejected because the state may be stale or unlocked. | Refresh and write through the guarded async state context. |
| Persisted state no longer matches its schema or cannot be serialized | The old state is ignored or the save fails. | Keep state values serializable and plan for stored sessions when fields change. |
| Hydration sends a snapshot without matching compiled defaults | The browser receives a larger full snapshot instead of a default diff. | Keep frontend initial-state hashes aligned with the backend defaults. |
| A partial router payload drops old connection data | Handlers or views read incomplete session or URL context. | Merge partial route data with the prior router context. |
| A replacement state is not marked as touched | Disk persistence can keep the replacement only in the process cache. | Mark replacement trees as changed before deferred or immediate persistence. |
| A newer navigation does not supersede old load work | Setup for an old page can run after the user moves to a new page. | Preserve supersession for page-load events. |
| A shared-state update targets a disconnected client | That client keeps its old view until reconnect hydration. | Use reconnect hydration to restore the complete state view. |
Key files
| File | Why to read it |
|---|---|
| reflex/state.py | Defines the state tree, declared and computed values, mutation tracking, hydration, snapshots, router context, and state updates. |
| packages/…/config.py | Defines state-manager selection and the option that controls explicit event-handler discovery. |
| reflex/…/delta.py | Shows how dirty state becomes a browser delta and how values are resolved for delivery. |
| reflex/…/proxy.py | Explains tracked mutable values and guarded state access for background work. |
| packages/…/base_state_processor.py | Shows handler execution, payload handling, chained events, and delta emission. |
| packages/…/event_processor.py | Shows the event queue, per-session ordering, task lifetime, and cancellation. |
| packages/…/state.js | Shows browser event queuing, socket transport, hydration gating, and delta dispatch. |
| reflex/…/__init__.py | Defines backend selection, state storage, tokens, and locking shared by the managers. |
| reflex/…/disk.py | Shows host-local persistence, state-tree restoration, deferred writes, expiry, and shutdown flushing. |
| reflex/…/memory.py | Illustrates process-local state and session expiry. |
| reflex/…/redis.py | Shows shared storage, distributed locks, state-part loading, and fenced writes. |
| reflex/…/shared.py | Shows linked state, update propagation, and client synchronization. |