Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

The Rerun Model

How Streamlit runs your script: it reruns top to bottom on every interaction, plain variables reset, widgets keep values, and st.stop and st.rerun control the flow.

If you remember only one thing about Streamlit, remember this: Streamlit runs your whole script from the first line to the last every time anything changes. A user drags a slider, types in a box, clicks a button, or you save the file: the script runs again from the top.

This is different from the event-driven code you may know from JavaScript or desktop apps, where a click handler runs and nothing else does. Once the rerun model feels natural, most Streamlit behavior stops being surprising. This lesson explains it with real Streamlit snippets and with a hand-written stand-in you can run.

What triggers a rerun

  • The user changes a widget value (slider, text input, selectbox, checkbox, file upload).
  • The user clicks a button. The button returns True only during the rerun it caused.
  • You edit and save the source file, and the user chooses "Rerun" (or "Always rerun") in the app's corner prompt.
  • The app calls st.rerun() itself.
  • A fragment or a timer asks for it (covered later in the course).

Each browser tab has its own session: its own widget values and its own run of the script. Two people using the same app do not affect each other.

sequenceDiagram
    participant U as User
    participant B as Browser
    participant S as Streamlit server
    U->>B: moves the slider to 20
    B->>S: new widget value
    S->>S: run app.py from line 1
    S-->>B: elements (changed ones are updated)
    B-->>U: page updates

The server sends the elements; the browser only changes what differs from the previous run.

Variables are forgotten, widgets are remembered

Because the script restarts, any ordinary variable is created again from scratch on every run. Widgets are different: Streamlit stores their current values on the server and gives them back to you.

Here is the classic beginner bug. This is real Streamlit code:

Python
import streamlit as st

count = 0
if st.button("Add one"):
    count += 1
st.write(f"Count: {count}")

The page shows a button and the text "Count: 0". Click the button: the script reruns, count is set to 0, the button returns True for this run only, so count becomes 1 and the page says "Count: 1". Click again: the script reruns, count is reset to 0 and the page shows 1 again. It never reaches 2, because count does not survive between runs. The fix is st.session_state (see the State and Caching chapter), a dictionary that Streamlit keeps for your session:

Python
import streamlit as st

if "count" not in st.session_state:
    st.session_state.count = 0

if st.button("Add one"):
    st.session_state.count += 1

st.write(f"Count: {st.session_state.count}")

A rerun engine you can run (stand-in)

The next block is not Streamlit. It is a miniature we wrote to make the rule visible. MiniApp.run() calls your script function again each time. st.slider and st.button return values the framework remembers (slider) or reports once (button). A state dictionary stands in for st.session_state.

Python Stand-in: variables reset, state persists

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.

After three clicks the plain variable still says 1, while the state version says 3. That difference is the single most important thing to learn about Streamlit.

Order matters: top to bottom

The script runs strictly in order, and elements appear in the order you call them. You can use a widget's return value only after the line that creates it:

Python
import streamlit as st

st.title("Order demo")
age = st.slider("Age", 0, 100, 30)      # widget created here
st.write("You are", age)                # uses the value after

Streamlit sends elements to the browser as they are produced, so a slow part of the script leaves the earlier parts already visible. A progress bar or a spinner placed before slow work gives the user feedback.

Controlling the run: st.stop and st.rerun

Sometimes the rest of the script does not make sense yet, for example when a user has not uploaded a file. st.stop() ends the current run right there, so nothing below it executes:

Python
import streamlit as st

uploaded = st.file_uploader("Choose a CSV")
if uploaded is None:
    st.info("Upload a file to continue.")
    st.stop()

st.write("File received:", uploaded.name)   # only reached with a file

st.rerun() does the opposite: it immediately starts a new run from the top. Use it when a change you made in code must be reflected at once in widgets drawn earlier in the script. Avoid calling it unconditionally, or it will rerun forever.

Why slow code hurts, and the cache idea

Because the whole script reruns on every click, an expensive step such as loading a large CSV or training a model would run again and again. Streamlit solves this with decorators @st.cache_data (for data) and @st.cache_resource (for shared objects like models or database connections), covered in the State and Caching chapter. The principle is simple: remember the result for the same inputs. You can see the idea in plain Python with functools.cache; this block is a stand-in for the concept, not Streamlit's decorator.

Python Stand-in: caching a slow step

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.

Six reruns, only two slow calls (for the values 4 and 5). Streamlit's cache decorators apply this idea to your whole app, with extra features such as time-to-live and per-session isolation.

Two practical consequences

  1. Do not rely on module-level variables for user data. They are rebuilt each run (and, if shared between users, can leak between sessions).
  2. Put expensive setup behind a cache and per-user memory in st.session_state. Everything else can stay plain Python.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user moves a slider. What does Streamlit do?

    Every interaction reruns the entire script; the slider simply returns its new value this time.
  2. 2. In the 'count = 0; if st.button(...): count += 1' app, why does the count never exceed 1?

    Plain variables are recreated on each run. Use st.session_state to keep a value across runs.
  3. 3. What does st.stop() do?

    It halts the current run at that line; the next interaction starts a new run as usual.
  4. 4. Two people open the same app at once. How do their sessions relate?

    Each browser session has its own script run and its own session state.
  5. 5. How long is the value returned by st.button True?

    A button returns True only in the run triggered by its click; on the next rerun it returns False again.

Summary

  • Streamlit reruns the entire script on every widget change, button click, file save or st.rerun().
  • Plain variables reset on each run; widgets and st.session_state keep values.
  • Buttons are True for exactly one run.
  • Use st.stop() to end a run early and st.rerun() to restart one.
  • Slow code should be cached so reruns stay fast.

Next: Magic, st.write and Page Configuration