Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท State and Caching

Callbacks, Forms and Fragments

Control when Streamlit reruns. Use on_change callbacks, st.form to batch inputs, st.fragment to rerun only part of the page, and st.rerun the right way.

By default every widget change reruns the whole script. That is simple, but it is not always what you want. A form with ten fields should not rerun ten times while someone types. A chart that updates every second should not make the whole page reload. A button should be able to change state before the page is drawn. Streamlit gives you three tools for this: callbacks, forms and fragments.

This lesson shows what each one does, the order in which things happen, and how to pick between them.

Callbacks: run code before the rerun

A callback is a function passed to a widget with on_change (inputs, sliders, selects) or on_click (buttons). When the user interacts, Streamlit runs the callback first, then reruns the script from the top. Inside the callback you can read and change st.session_state; the new values are already in place when the script body runs.

Python
import streamlit as st

def double():
    st.session_state.value *= 2

st.session_state.setdefault("value", 1)
st.button("Double it", on_click=double)
st.write("Value:", st.session_state.value)

Without a callback you could write if st.button(...): st.session_state.value *= 2 above the display line, and the page would look the same. Callbacks shine when the order matters. The classic case is resetting a widget:

Python
def clear_name():
    st.session_state.name = ""        # allowed here, before the widget exists

st.text_input("Name", key="name")
st.button("Clear", on_click=clear_name)

Doing the same with if st.button("Clear"): st.session_state.name = "" after the text input fails, because the input was already created in this run.

Callbacks take arguments through args and kwargs:

Python
def add(n):
    st.session_state.total += n

st.button("+1", on_click=add, args=(1,))
st.button("+10", on_click=add, args=(10,))

A few rules to remember:

  • A callback runs on the interaction, before the rest of the script. Code after the widget in the same run sees the new state.
  • Do not draw anything (st.write) in a callback. The output would be discarded, since a rerun follows right away.
  • If the callback raises an exception, the error appears at the top of the page.

The stand-in below models the order of events: callback first, then the rerun.

Python Stand-in: callback runs before the rerun

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every click logs callback runs before script starts, so the page is never one step behind.

Forms: batch several inputs

Every widget normally triggers a rerun on its own. In a data-entry screen this is annoying and slow. st.form groups widgets and holds back their values until the user presses the form submit button. Nothing inside reruns the script until then.

Python
import streamlit as st

with st.form("signup"):
    name = st.text_input("Name")
    email = st.text_input("Email")
    age = st.number_input("Age", 0, 120, 18)
    agreed = st.checkbox("I accept the terms")
    submitted = st.form_submit_button("Create account")

if submitted:
    if not agreed:
        st.error("Please accept the terms.")
    else:
        st.success(f"Welcome, {name}!")

Rules for forms:

  • A form needs exactly one st.form_submit_button. It returns True only on the run triggered by the click.
  • A regular st.button is not allowed inside a form.
  • Widgets inside can have keys, and st.session_state holds their values as of the last submit.
  • Callbacks are allowed only on the submit button (on_click), not on inner widgets.
  • Pass clear_on_submit=True to empty the fields after a successful submit.
  • Widgets inside a form cannot change other widgets inside the same form instantly, because nothing reruns. If a dropdown must change another dropdown live, keep them outside the form.

The stand-in simulates the idea: edits go into a "browser" buffer, and the script only sees them at submit.

Python Stand-in: a form batches edits until submit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two edits cost zero reruns. Only the submit triggered one.

Fragments: rerun only part of the page

Sometimes a rerun of the whole script is too heavy for a small interaction. A fragment is a function decorated with @st.fragment. Interacting with a widget inside the fragment reruns only that function, not the rest of the script.

Python
import streamlit as st

@st.fragment
def live_counter():
    if st.button("Add one", key="inc"):
        st.session_state.n = st.session_state.get("n", 0) + 1
    st.write("Clicks:", st.session_state.get("n", 0))

st.title("Dashboard")
data = load_big_dataset()        # not rerun by the button inside the fragment
live_counter()
st.write("Rows:", len(data))

When the button is pressed, only live_counter runs again. Everything outside keeps its current output. Fragments are ideal for filters on one chart, a refresh button on one widget or a small chat box.

Useful options and rules:

  • @st.fragment(run_every="10s") reruns the fragment on a timer, making auto-refreshing tiles easy (a live clock, a metrics tile).
  • To make the whole app rerun from inside a fragment, call st.rerun(). In newer versions st.rerun(scope="app") states this explicitly, and scope="fragment" reruns only the fragment.
  • A fragment can read values from outside, but it must not draw widgets outside itself. Writing into containers created outside the fragment is limited: elements created outside can be updated only from within the fragment run in specific ways, so keep the output inside the fragment.
  • Widgets inside a fragment keep their state in st.session_state like any other.

This stand-in counts how many lines of "expensive work" run with and without a fragment.

Python Stand-in: a fragment avoids the expensive part

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three clicks ran the heavy function three times without a fragment, and once (the first load) with it. Caching solves the same problem at the data level, and the two combine well.

Choosing the right tool

flowchart TD
    Q{"What do you need?"} --> A["Change state before the page draws<br/>or reset a widget"]
    Q --> B["Collect many inputs,<br/>react once"]
    Q --> C["Update one part,<br/>keep the rest untouched"]
    A --> CB["Callback<br/>on_click / on_change"]
    B --> FM["st.form"]
    C --> FR["st.fragment"]

Callbacks decide when state changes, forms decide when inputs are sent, fragments decide how much reruns.

Using st.rerun() safely

st.rerun() is a last resort for cases where state changed after the widgets that depend on it were drawn. A typical valid use is after saving to a database:

Python
if submitted:
    save_to_database(name, email)
    st.session_state.saved = True
    st.rerun()                        # redraw the page with the new data

Keep an exit condition: make sure the state that triggered the rerun cannot be true forever, or the app loops.

Common mistakes

  • Putting st.button inside st.form (use st.form_submit_button).
  • Writing to a widget key after the widget exists instead of in a callback.
  • Forgetting that form values change only at submit, then reading stale values.
  • Calling st.write inside a callback and wondering where the output went.
  • Expecting a fragment to update elements drawn outside it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order do a button's on_click callback and the script run?

    Streamlit executes the callback, and then reruns the script, so state is already updated when widgets are created.
  2. 2. What does st.form change about reruns?

    A form batches inputs. Nothing inside it triggers a rerun until the form submit button is pressed.
  3. 3. Which is NOT allowed inside st.form?

    Regular buttons cannot live in a form. Use st.form_submit_button, which returns True on the submitting run.
  4. 4. What does @st.fragment do?

    Interacting with a widget inside a fragment reruns just the fragment, so the rest of the script, and its expensive work, is skipped.
  5. 5. Why use a callback to clear a text input?

    Widget state can only be set before the widget is instantiated in a run. Callbacks execute first.

Summary

  • Callbacks (on_click, on_change) run before the script reruns and are the right place to change state or reset widgets.
  • st.form batches widget values and reruns only when the form submit button is pressed.
  • @st.fragment reruns only the decorated function on interaction; run_every makes timed refreshes.
  • st.rerun() forces a new run; always make sure it cannot loop forever.
  • Combine these with caching to keep large apps responsive.

Next: Caching: cache_data and cache_resource