State Management
marimo providesmo.state() for managing mutable reactive state in your notebooks. While marimo’s built-in reactivity handles most use cases, state() enables advanced patterns like synchronized UI elements and side effects.
Understanding marimo.state()
Themo.state() function creates mutable reactive state that triggers automatic re-execution of dependent cells when updated.
Basic Usage
- Getter function: Reads the current state value
- Setter function: Updates the state value and triggers reactivity
Reading State
Updating State
Reactivity Behavior
When you call a state setter:- The state value is updated
- All other cells that reference the getter are automatically re-run
- By default, the cell that called the setter is not re-run (preventing infinite loops)
Self-Loops
To allow a cell to re-run itself when calling the setter:Common Use Cases
Synchronizing Multiple UI Elements
Bind multiple UI elements to shared state so they stay synchronized:When either element is updated, both will reflect the new value automatically.
Tracking User Interactions
Building State Machines
Implementation Details
State Registry
marimo maintains a state registry that tracks all state instances in your notebook. Frommarimo/_runtime/state.py:
- Uses weak references to avoid memory leaks
- Prunes inactive states when cells are deleted
- Maintains bidirectional mappings for efficient lookups
SetFunctor
The setter is implemented as a typed functor that handles both direct values and functional updates:Best Practices
Do: Use for UI synchronization
Do: Use for UI synchronization
State is ideal for keeping multiple UI elements in sync or managing UI-driven side effects.
Don't: Store UI elements in state
Don't: Store UI elements in state
Never store
marimo.ui elements in state - this can cause hard-to-diagnose bugs and breaks reactivity.Do: Prefer built-in reactivity
Do: Prefer built-in reactivity
For most cases, marimo’s automatic reactivity is sufficient:
Don't: Mutate state directly
Don't: Mutate state directly
Always use the setter function - never mutate the state value directly.
Testing State
From the test suite (tests/_runtime/test_state.py):
When to Use State
Usemo.state() when:
- Synchronizing multiple UI elements to the same value
- Implementing complex UI interaction patterns
- Building state machines or multi-step workflows
- Triggering side effects from UI interactions
mo.state() when:
- Simple variable assignment works (use marimo’s built-in reactivity)
- You’re just reading UI element values (use
.valuedirectly) - You need to store computation results (use regular variables)
Related APIs
- Reactivity - Understanding marimo’s reactive execution
- Interactivity - Working with UI elements
- UI Elements - Available interactive components