Streamlit Session State

By default, Streamlit re-runs your script top to bottom whenever a user interacts with a widget
What this means is that all variables resets unless you use Session State
 
Need a Streamlit developer?: Click Here

Introduction

st.session_state allows us to
Preserve values across reruns
Store user inputs, counters or configurations
Share data between widgets and callbacks
Mange app state like in traditional web apps we come across on the internet.
Here, the count persists across clicks (without resetting)
				
					st.title("Session State Basics")


#Initialize a key if is not already set
if "count" not in st.session_state:
    st.session_state.count = 0
    #we can also use st.session_state["count"] = 0


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

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

if st.button("Reset"):
    st.session_state.count = 0



				
			

Accession Session State

we have two main ways of accessing session state
Dictionary-like syntax
Attribute-style access
				
					#Dictionary-like syntax
st.session_state["name"] = "Alice"
st.write(st.session_state["name"])


				
			
				
					#Attribute-style access
st.session_state.name = "Alice"
st.write(st.session_state.name)



				
			

Widget + Session State Binding


Each widget can be tied to a session state variable using the “key” parameter

				
					location = st.text_input("Enter your location", key="userlocation")
st.write("welcome to", st.session_userlocation)
				
			

Callbacks with Session State

widgets can trigger callbacks on value change
callback functions are functions used in another functions
callback fires when value changes
				
					def handle_change():
    st.write("you typed:", st.session_state.user_input)

st.text_input("Type something", key="user_input", on_change=handle_change)


				
			

Counter App using Session State

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

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

st.write("Counter:", st.session_state.counter)


				
			

Login Form

				
					with st.form("Login"):
    username = st.text_input("Username", key="user")
    password = st.text_input("Password", type="password", key="pwd")
    submit = st.form_submit_button("Login")

if submit:
    if username == "admin" and password == "1234":
        st.session_state.logged_in = True
        st.success("Welcome, Admin")
    else:
        st.error("Invalid credentials!")

if "logged_in" in st.session_state and st.session_state.logged_in:
    st.write("You are logged in 🎉")


				
			

Multi-Page Navigation

				
					if "page" not in st.session_state:
    st.session_state.page = "Home"

if st.button("🏠 Home"):
    st.session_state.page = "Home"
if st.button("📊 Dashboard"):
    st.session_state.page = "Dashboard"

if st.session_state.page == "Home":
    st.write("Welcome to Home Page")
elif st.session_state.page == "Dashboard":
    st.write("Dashboard Content Here")

				
			

Search Filter with Memory

				
					import pandas as pd

data = {"Name": ["Alice", "Bob", "Charlie", "David"], "Age": [25, 30, 35, 40]}
df = pd.DataFrame(data)

search = st.text_input("Search Name", key="search")

if st.session_state.search:
    results = df[df["Name"].str.contains(st.session_state.search, case=False)]
    st.write(results)
else:
    st.write(df)

				
			

Best Practices

  • Always initialize session state variables before use.

  •  Use descriptive key names for widgets.

  •  Group related variables in dict-like structures inside session_state.

  • Avoid overusing session state for large datasets → use st.cache_data instead.

  • Don’t store sensitive data (e.g., plain-text passwords).

 

Want to learn more about Streamlit?: Click Here

 

Watch videos on Streamlit:

Leave a Reply

Your email address will not be published. Required fields are marked *