A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
docs: warn users more strongly against using mo.state() and on_change handlers. (#3266)
Akshay Agrawal90f55bea7f1b
diff --git a/docs/api/state.md b/docs/api/state.mdindex f24050e1f4..9978036916 100644--- a/docs/api/state.md+++ b/docs/api/state.md@@ -1,10 +1,13 @@# State-!!! warning "Advanced topic!"+!!! warning "Stop! Read the interactivity guide first!"+ **Read the guide on [creating interactive+ elements](../guides/interactivity.md)** before reading this one!- This API doc covers reactive state (`mo.state`), an advanced topic.+!!! warning "Advanced topic!"+ This guide covers reactive state (`mo.state`), an advanced topic.- **You likely don't need reactive state**. UI elements already have built-in+ **You likely don't need `mo.state`**. UI elements already have built-instate, their associated value, which you can access with their `value` attribute.For example, `mo.ui.slider()` has a value that is its current position on aninterval, while `mo.ui.button()` has a value that can be configured to@@ -12,15 +15,13 @@`False`. Additionally, interacting with UI elements bound to global variables[automatically executes cells](../guides/interactivity.md) that reference thosevariables, letting you react to changes by just reading their- `value` attributes. This functional paradigm is the preferred way of- reacting to UI interactions in marimo. So if you- think you need to use `mo.state`, make sure to first read the [guide on- interactivity](../guides/interactivity.md). Chances are, the reactive execution- built into UI elements will suffice. (For example, [you don't need reactive- state to handle a button click](../recipes.md#working-with-buttons).)-+ `value` attributes. **This functional paradigm is the preferred way of+ reacting to UI interactions in marimo.** **Chances are, the reactive+ execution built into UI elements will suffice.** (For example, [you don't need+ reactive state to handle a button click](../recipes.md#working-with-buttons).)That said, here are some signs you might need `mo.state`:+- you need to maintain historical state related to a UI element that can'tbe computed from its built-in `value` (_e.g._, all values the user hasever input into a form)@@ -28,9 +29,7 @@interacting with either one controls the other)- you need to introduce cycles across cells- If one of these cases applies to you, then read on. `mo.state` lets you- make all kinds of interesting applications, but like mutable state in general,- it can complicate notebook development and has the potential to- introduce hard-to-find bugs.+ **In over 99% of cases, you don't need and shouldn't use `mo.state`.** This+ feature can introduce hard-to-find bugs.::: marimo.statediff --git a/docs/guides/best_practices.md b/docs/guides/best_practices.mdindex 5bf132dee1..bf03fd0ee8 100644--- a/docs/guides/best_practices.md+++ b/docs/guides/best_practices.md@@ -66,6 +66,9 @@ instead of mutating existing ones.```pythonextended_list = l + [new_item()]```+**Don't use state and `on_change` handlers.** Don't use `on_change` handlers+to react to UI interactions. Instead, use marimo's built-in [reactive execution+for interactive elements](../guides/interactivity.md).**Write idempotent cells.**Write cells whose outputs and behavior are the samediff --git a/docs/guides/interactivity.md b/docs/guides/interactivity.mdindex 89e2793789..104915ae57 100644--- a/docs/guides/interactivity.md+++ b/docs/guides/interactivity.md@@ -34,7 +34,7 @@ assigned to a global variable.**Display UI elements in the output area above a cell by including them in thelast expression, just like any other object. You can also embed elements-in [markdown][marimo.md]using Python f-strings, like so:+in [markdown][marimo.md] using Python f-strings, like so:```python3slider = mo.ui.slider(1, 10)diff --git a/docs/guides/state.md b/docs/guides/state.mdindex 5650ee7276..f57b889ae5 100644--- a/docs/guides/state.md+++ b/docs/guides/state.md@@ -1,9 +1,13 @@# Reactive state+!!! warning "Stop! Read the interactivity guide first!"+ **Read the guide on [creating interactive+ elements](../guides/interactivity.md)** before reading this one!+!!! warning "Advanced topic!"This guide covers reactive state (`mo.state`), an advanced topic.- **You likely don't need reactive state**. UI elements already have built-in+ **You likely don't need `mo.state`**. UI elements already have built-instate, their associated value, which you can access with their `value` attribute.For example, `mo.ui.slider()` has a value that is its current position on aninterval, while `mo.ui.button()` has a value that can be configured to@@ -11,15 +15,13 @@`False`. Additionally, interacting with UI elements bound to global variables[automatically executes cells](../guides/interactivity.md) that reference thosevariables, letting you react to changes by just reading their- `value` attributes. This functional paradigm is the preferred way of- reacting to UI interactions in marimo. So if you- think you need to use `mo.state`, make sure to first read the [guide on- interactivity](../guides/interactivity.md). Chances are, the reactive execution- built into UI elements will suffice. (For example, [you don't need reactive- state to handle a button click](../recipes.md#working-with-buttons).)-+ `value` attributes. **This functional paradigm is the preferred way of+ reacting to UI interactions in marimo.** **Chances are, the reactive+ execution built into UI elements will suffice.** (For example, [you don't need+ reactive state to handle a button click](../recipes.md#working-with-buttons).)That said, here are some signs you might need `mo.state`:+- you need to maintain historical state related to a UI element that can'tbe computed from its built-in `value` (_e.g._, all values the user hasever input into a form)@@ -27,10 +29,8 @@interacting with either one controls the other)- you need to introduce cycles across cells- If one of these cases applies to you, then read on. `mo.state` lets you make- all kinds of interesting applications, but like mutable state in general,- it can complicate notebook development and has the potential to- introduce hard-to-find bugs.+ **In over 99% of cases, you don't need and shouldn't use `mo.state`.** This+ feature can introduce hard-to-find bugs.You can build powerful, interactive notebooks and apps using just `mo.ui` andreactivity.@@ -47,16 +47,21 @@ But sometimes, you might want interactions to mutate state:<figcaption>A proof-of-concept TODO list made using state.</figcaption></div>-- You want to tie two different UI elements so that updating one updates- the other.+- You want to tie two different UI elements so that updating **either** one+ updates the other.<div align="center" style="margin-top:2rem; margin-bottom:2rem"><figure><img src="/_static/docs-state-tied.gif"/>-<figcaption>Use state to tie two elements together.</figcaption>+<figcaption>Use state to tie two elements together in a cycle.</figcaption></figure></div>+!!! warning "Use reactive execution for uni-directional flow"+ If you just want the value of a single element to update another element,+ then **you shouldn't use `mo.state`**. Instead, use marimo's built-in+ reactive execution --- see the [interactivity guide](`../guides/interactivity.md`).+For cases like these, marimo provides the function [`mo.state()`](../api/state.md),which creates a state object and returns a getter and setter function. When youcall the setter function in one cell, all other cells that reference the getter@@ -135,9 +140,10 @@ the new value of the element and does anything with it. You can use the setterfunction in an `on_change` callback to mutate state.!!! note "Use state sparingly"- You can get far using just `mo.ui`, without state. But judiciously using- state can simplify the implementation of highly interactive notebooks/apps, and- also enables new use cases. The next few examples showcase good uses of state.+ You can get far using just `mo.ui`, without state, because marimo+ automatically runs cells that reference UI elements on interaction+ (see the [interactivity guide](../guides/interactivity.md)). Only+ use `on_change` callbacks as a last resort!### Example: counterdiff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.pyindex 3c7324defe..854be200d9 100644--- a/marimo/_runtime/state.py+++ b/marimo/_runtime/state.py@@ -173,9 +173,16 @@ def state("""Mutable reactive state.+ Warning: reactive state is an advanced feature that you likely don't need;+ it makes it possible to introduce cycles and hard-to-debug code execution+ paths. **In almost all cases, you should prefer using marimo's built-in+ [reactive execution](https://docs.marimo.io/guides/reactivity) and+ [interactivity](https://docs.marimo.io/guides/interactivity).**+This function takes an initial value and returns:- - a getter function that reads the state value- - a setter function to set the state's value++ - a getter function that reads the state value+ - a setter function to set the state's valueWhen you call the setter function and update the state value in one cell,all *other* cells that read any global variables assigned to the getter@@ -185,10 +192,14 @@ def state(`allow_self_loops=True`.You can use this function with `UIElement` `on_change` handlers to trigger- side-effects when an element's value is updated. For example, you can tie- multiple UI elements to derive their values from shared state.+ side-effects when an element's value is updated; however, you should+ prefer using marimo's built-in [reactive execution for interactive+ elements](https://docs.marimo.io/guides/interactivity).++ For example, you can tie multiple UI elements to derive their values from+ shared state.- Example usage:+ Examples:Create state:```pythonget_count, set_count = mo.state(0)@@ -206,7 +217,8 @@ def state(set_count(lambda value: value + 1)```- Never mutate the state directly. You should only change its value through its setter.+ Never mutate the state directly. You should only change its value through+ its setter.**Synchronizing multiple UI elements:**```pythondiff --git a/mkdocs.yml b/mkdocs.ymlindex 0f84918550..9467f8d4d6 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -118,9 +118,9 @@ nav:- Overview: guides/integrating_with_marimo/index.md- Custom UI plugins: guides/integrating_with_marimo/custom_ui_plugins.md- Displaying objects: guides/integrating_with_marimo/displaying_objects.md- - State management: guides/state.md- Best practices: guides/best_practices.md- Troubleshooting: guides/troubleshooting.md+ - Dangerously set state: guides/state.md- API Reference:- Overview: api/index.md- Markdown: api/markdown.md