Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท State and Caching

Session State

Learn st.session_state in Streamlit: initialize once, read and write with keys, link widgets to state, build counters, to-do lists and multi-step flows.

Since the script reruns on every interaction, an app needs a place to keep values between runs. That place is st.session_state, a dictionary-like object that belongs to one browser session. Each visitor (each open tab session) gets their own, so two people using your app at once never see each other's data.

You use it for counters, shopping carts, chat histories, multi-step forms, the currently selected row, and anything else that must still be there after the script starts over. Session state is also how widgets talk to each other and how your code can set a widget's value.

Reading, writing and initializing

Session state works like a dictionary, with attribute access as a shortcut:

Python
import streamlit as st

if "count" not in st.session_state:
    st.session_state.count = 0          # initialize once

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

st.write("Count:", st.session_state.count)

The if "count" not in ... guard is the initialization pattern. It runs the assignment only on the first run of a session. Without the guard, the line would reset the counter on every rerun, which is the bug from the previous lesson. Reading a key that was never set raises an error, so always initialize before reading.

Both spellings are equivalent: st.session_state["count"] and st.session_state.count. Use the bracket form when the key is not a valid identifier or comes from a variable. You can also use .get("count", 0), del st.session_state["count"], in, .items() and .update({...}).

The next TryIt rebuilds the counter with a stand-in. SessionState mimics the dictionary behaviour and the run function mimics a rerun.

Python Stand-in: the initialization pattern

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.

The count now climbs 0, 1, 2, 2, 3, because the dictionary outlives each call.

Per-user, not global

Session state is isolated per session. Two browsers each get a separate dictionary, and a new browser tab starts a new session. A page refresh also starts a new session: the old state is gone, because it lives in server memory tied to the connection. If you need data that survives a refresh or is shared across users, store it in a database, a file, or a cache (see Caching and SQL databases).

Python
st.session_state.setdefault("history", [])    # shorthand for the init guard
st.session_state.history.append("opened app")

setdefault is handy for lists and dictionaries, since it creates them only when missing.

Widgets and keys

Every widget can take a key. The key does two things: it gives the widget a stable identity, and it stores the widget's value in session state under that key.

Python
import streamlit as st

st.text_input("Your name", key="user_name")
st.write("Hello,", st.session_state.user_name or "stranger")

Now other parts of the app can read the name without the variable being passed around. You can also read it before the widget is drawn on a later run, because the value is kept. This makes widgets in different columns, tabs or pages share data easily.

Keys also solve a different problem. Two widgets with the same label and parameters are indistinguishable, and Streamlit raises a DuplicateWidgetID error. Giving them different keys fixes this, which is common when you create widgets in a loop:

Python
for item in ["tea", "coffee", "juice"]:
    st.number_input(f"How many {item}?", min_value=0, key=f"qty_{item}")

Setting a widget's value

You can set the value of a keyed widget by writing to its key, but only before the widget is created in the current run. Setting it after raises an error. The usual way is inside a callback (below) or at initialization:

Python
if "volume" not in st.session_state:
    st.session_state.volume = 40              # the default for the slider
st.slider("Volume", 0, 100, key="volume")     # do not also pass value=

Passing both value= and a pre-set state for the same key makes Streamlit warn that the widget was given a default and a state value. Choose one source of truth: either the state, or the value argument.

When a widget disappears

If a widget is not drawn in a run (for example it sits inside an if that is now false), Streamlit drops its state. When it comes back it starts at the default again. To keep a value across such gaps, copy it into a second key that is not tied to a widget, or re-assign the key to itself at the top of the script:

Python
st.session_state.filter = st.session_state.get("filter", "all")

Callbacks

Widgets accept an on_change (or on_click for buttons) function. Streamlit calls it before the script reruns, so the state is already updated when the page is drawn.

Python
import streamlit as st

def add_item():
    text = st.session_state.new_item.strip()
    if text:
        st.session_state.items.append(text)
    st.session_state.new_item = ""            # clear the box: allowed inside a callback

st.session_state.setdefault("items", [])
st.text_input("New item", key="new_item", on_change=add_item)
for item in st.session_state.items:
    st.write("-", item)

Clearing the text input by assigning to its key works only inside the callback, because callbacks run before widgets are created in the next run. Pass arguments with args=(...) and kwargs={...}. The next lesson, Callbacks, Forms and Fragments, covers them in depth.

A to-do list you can run

This stand-in models a to-do app with an add-callback and a remove button. Notice that the "script" is called after each simulated event, and the list survives because it lives in the session store.

Python Stand-in: a to-do list in session state

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.

The blank entry was ignored by the callback, and removing item 0 left only the second entry.

Multi-step flows

State lets one page act like a wizard. Keep a step number in state and show a different block for each step:

Python
import streamlit as st

st.session_state.setdefault("step", 1)

if st.session_state.step == 1:
    st.text_input("Email", key="email")
    st.button("Next", on_click=lambda: st.session_state.update(step=2))
elif st.session_state.step == 2:
    st.write("Confirm:", st.session_state.email)
    st.button("Back", on_click=lambda: st.session_state.update(step=1))

Notice the stored email stays available on step 2, even though step 2 does not draw the email widget. Because that widget key was not rendered on step 2, Streamlit would normally clean it up; to be safe, copy the value into a normal state key (st.session_state.saved_email = st.session_state.email) in the callback that moves to the next step.

What to store

Session state can hold any Python object, but keep it lean. It lives in server memory for as long as the session is open, and large frames copied into state for every user add up quickly. Prefer ids, small settings and user choices, and load large data through a cache. Objects that cannot be pickled (open connections) can be stored but are not safe across server restarts, and some Streamlit deployments pickle state.

Common mistakes

  • Forgetting the init guard, so a value is reset on every run.
  • Assigning to a widget key after the widget is already created in the run (StreamlitAPIException).
  • Using the same key for two widgets.
  • Storing huge DataFrames per user.
  • Assuming state survives a browser refresh. It does not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why wrap st.session_state.count = 0 in if "count" not in st.session_state?

    Without the guard the assignment executes on every rerun and resets the value. The guard runs it once per session.
  2. 2. What does the key argument of a widget do?

    A key makes the widget unique and lets you read or set its value through st.session_state[key].
  3. 3. What happens to session state when the user refreshes the browser page?

    State lives in server memory tied to the browser session. A refresh creates a new session. Use a database to persist data.
  4. 4. Why can a callback clear a text input by assigning to its key, while code after the widget cannot?

    A widget's state can only be changed before it is instantiated in a run. Callbacks run first, so they can.

Summary

  • st.session_state is a per-session dictionary that persists across reruns.
  • Initialize with if key not in st.session_state or setdefault.
  • Widget keys identify widgets and expose their values in session state.
  • You can set a keyed widget's value only before it is created in the run, typically in a callback.
  • A widget that is not drawn loses its state, so copy important values elsewhere.
  • Session state is lost on refresh; use a database for durable data.

Next: Callbacks, Forms and Fragments