Session State in Streamlit

When you build apps with Streamlit, the script reruns from top to bottom every time a user interacts (clicks a button, changes input, etc.). Without state management, variables reset on each rerun.

👉 Session State solves this by storing data per user session.

What is Session State?

Session State is a dictionary-like storage that persists values across reruns for a single user.

Think of it as:

Why Session State is Needed

Without Session State

Python

import streamlit as st

count = 0

if st.button("Increase"):
    count += 1

st.write(count)   

👉 Output always shows 0 because the script reruns.

With Session State

Python

import streamlit as st

# Initialize session variable
if "count" not in st.session_state:
    st.session_state.count = 0

# Update state
if st.button("Increase"):
    st.session_state.count += 1

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

How Session State Works

Internally:

Basic Syntax

Initialize

if "key" not in st.session_state:
    st.session_state.key = value    

Read

st.session_state.key    

Update

st.session_state.key = new_value    

Delete

# Delete a single key in session state
del st.session_state.key

# Delete all items in session state
for key in st.session_state.keys():
    del st.session_state[key]    

Example: User Name Persistence

Python

import streamlit as st

# Initialize
if "name" not in st.session_state:
    st.session_state.name = ""

# Input
name_input = st.text_input("Enter your name")

# Save to session
if st.button("Save"):
    st.session_state.name = name_input

st.write("Saved Name:", st.session_state.name)    

What Happens

Callback Functions with Session State

Callbacks update state before rerun.

Python

import streamlit as st

def update_count():
    st.session_state.count += 1

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

st.button("Increase", on_click=update_count)

st.write(st.session_state.count)