> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Session State

> Maintain application state and data across user interactions and reruns

Every time a user interacts with a widget (clicks a button, types in a text box, or adjusts a slider), **Streamlit reruns the entire Python script from top to bottom**.

By default, any local variables you declare are reset to their original values during a rerun. To preserve values and pass data across runs, you must use **Session State** (`st.session_state`).

***

## 1. How Session State Works

`st.session_state` behaves like a Python dictionary. You can store key-value pairs that persist throughout a user's session.

### Initializing values

Always check if a key exists in session state before using or modifying it, otherwise you will re-initialize it on every rerun:

```python theme={null}
if "counter" not in st.session_state:
    st.session_state.counter = 0
```

### Reading and Writing values

You can access and update keys using either attribute or dictionary syntax:

```python theme={null}
# Read
current_val = st.session_state.counter

# Write / Update
st.session_state.counter += 1
```

***

## 2. Practical Example: Student Grade Logger

Here is a practical example of using session state to store a list of logged students. Each time you click the "Add Student" button, the script reruns, but the list of students is preserved and updated.

Create a file named `exercise_session_state.py`:

```python theme={null}
import streamlit as st

st.set_page_config(page_title="Student Log", layout="centered")

st.title("🎓 Student Performance Logger")
st.write("This app uses Session State to keep track of added students without losing data on reruns.")

# 1. Initialize session state list if it doesn't exist
if "student_logs" not in st.session_state:
    st.session_state.student_logs = []

# Form to input student details
with st.form("student_form", clear_on_submit=True):
    name = st.text_input("Student Name")
    score = st.slider("Exam Score", 0, 100, 75)
    submit = st.form_submit_button("Add Student")
    
    if submit:
        if name.strip() != "":
            # 2. Append new student log to session state list
            st.session_state.student_logs.append({"name": name, "score": score})
            st.success(f"Added {name}!")
        else:
            st.error("Please enter a name.")

st.divider()

# Display log from session state
st.subheader("📋 Logged Student Records")
if len(st.session_state.student_logs) > 0:
    for idx, student in enumerate(st.session_state.student_logs):
        st.write(f"{idx + 1}. **{student['name']}** — Score: {student['score']}%")
    
    # 3. Clear button to empty the session state list
    if st.button("Clear Log"):
        st.session_state.student_logs = []
        st.rerun() # Forces a rerun to update the UI immediately
else:
    st.info("No students logged yet.")
```

Run the script:

```bash theme={null}
streamlit run exercise_session_state.py
```
