STATE MANAGEMENT & VARIABLES: 10 REAL-TIME APPLICATIONS WITH `gr.State`

Learn how to preserve user session data, maintain conversation histories, build multi-step workflows, and store temporary states across interactions using gr.State in Gradio.

⚡ Understanding Session State in Gradio (`gr.State`)

By default, Gradio functions are stateless. Every time a user interacts with a component, the function executes freshly without remembering past values. gr.State allows you to store session variables safely across user interactions, enabling features like shopping carts, chat memory, multi-step wizards, and calculation histories.

Example 1: Persistent Click Counter
Tracks and increments an integer counter stored inside a session state variable across multiple button clicks.
Python (state_ex1.py)
import gradio as gr

def count_clicks(current_count):
    new_count = current_count + 1
    return new_count, f"Button has been clicked {new_count} times."

with gr.Blocks() as demo:
    gr.Markdown("### Persistent Session Counter")
    click_state = gr.State(value=0) # Initialize state variable
    
    btn = gr.Button("Click Me!")
    output = gr.Textbox(label="Status")
    
    btn.click(fn=count_clicks, inputs=click_state, outputs=[click_state, output])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Persistent Session Counter

Button has been clicked 3 times.
Example 2: Simple Chatbot Memory (`gr.State` for Chat History)
Appends user inputs and assistant responses to a stored list history object inside `gr.State`.
Python (state_ex2.py)
import gradio as gr

def chat_reply(user_message, history):
    history = history or []
    bot_response = f"Echo: {user_message}"
    history.append((user_message, bot_response))
    return history, history, ""

with gr.Blocks() as demo:
    gr.Markdown("### Stateful Chat Memory")
    chatbot = gr.Chatbot(label="Conversation History")
    state = gr.State([]) # Stores list of tuples
    
    txt = gr.Textbox(label="Your Message", placeholder="Type here...")
    txt.submit(chat_reply, inputs=[txt, state], outputs=[chatbot, state, txt])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Stateful Chat Memory

User: Hello!
Bot: Echo: Hello!
Type here...
Example 3: E-Commerce Shopping Cart Accumulator
Adds selected items to a cumulative shopping cart list stored in session state.
Python (state_ex3.py)
import gradio as gr

def add_to_cart(item, cart):
    cart.append(item)
    return cart, f"Current Cart Items: {', '.join(cart)}"

with gr.Blocks() as demo:
    gr.Markdown("### E-Commerce Shopping Cart")
    cart_state = gr.State([])
    
    item_drop = gr.Dropdown(choices=["Laptop ($1200)", "Mouse ($25)", "Keyboard ($75)"], label="Select Product")
    add_btn = gr.Button("Add to Cart")
    cart_display = gr.Textbox(label="Cart Summary")
    
    add_btn.click(add_to_cart, inputs=[item_drop, cart_state], outputs=[cart_state, cart_display])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### E-Commerce Shopping Cart

Select Product: Laptop ($1200) ▼
Current Cart Items: Laptop ($1200), Mouse ($25)
Example 4: Multi-Step Form Wizard Data Collector
Collects user inputs across multiple wizard steps and aggregates them into a final dictionary state.
Python (state_ex4.py)
import gradio as gr

def save_step1(name, data):
    data["name"] = name
    return data, gr.update(visible=False), gr.update(visible=True)

with gr.Blocks() as demo:
    gr.Markdown("### Multi-Step Registration")
    form_data = gr.State({})
    
    with gr.Column(visible=True) as step1:
        n_box = gr.Textbox(label="Full Name")
        btn1 = gr.Button("Next")
        
    with gr.Column(visible=False) as step2:
        e_box = gr.Textbox(label="Email Address")
        btn2 = gr.Button("Submit All")
        
    btn1.click(save_step1, inputs=[n_box, form_data], outputs=[form_data, step1, step2])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Multi-Step Registration (Step 1 Active)

Full Name: Nikita Sharma
Example 5: Quiz Score Tracker & Assessment Engine
Accumulates total quiz points in a persistent state variable across dynamic question submissions.
Python (state_ex5.py)
import gradio as gr

def submit_answer(ans, score):
    points = 1 if ans == "Python" else 0
    new_score = score + points
    return new_score, f"Answer Correct! Current Score: {new_score}/5"

with gr.Blocks() as demo:
    gr.Markdown("### Interactive Quiz")
    score_state = gr.State(0)
    
    ans_radio = gr.Radio(["Python", "Java", "C++"], label="Q1: Which language is interpreted?")
    submit_btn = gr.Button("Submit Answer")
    feedback = gr.Textbox(label="Feedback")
    
    submit_btn.click(submit_answer, inputs=[ans_radio, score_state], outputs=[score_state, feedback])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Interactive Quiz

Q1: Which language is interpreted?
◉ Python ○ Java ○ C++
Answer Correct! Current Score: 1/5
Example 6: Multi-Step Undo / Redo History Buffer
Maintains a text modification history stack allowing users to undo changes using state.
Python (state_ex6.py)
import gradio as gr

def update_text(new_val, history):
    history.append(new_val)
    return history, new_val

def undo_text(history):
    if len(history) > 1:
        history.pop()
        return history, history[-1]
    return history, history[0] if history else ""

with gr.Blocks() as demo:
    gr.Markdown("### Text Editor with Undo Buffer")
    history_state = gr.State([""])
    
    txt_box = gr.Textbox(label="Editor")
    undo_btn = gr.Button("↩ Undo")
    
    txt_box.change(update_text, inputs=[txt_box, history_state], outputs=[history_state, txt_box])
    undo_btn.click(undo_text, inputs=history_state, outputs=[history_state, txt_box])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Text Editor with Undo Buffer

Editor Text Area Content...
Example 7: Turn-Based Game Score & Round Tracker
Keeps track of active game round numbers and player scores across interactive turns.
Python (state_ex7.py)
import gradio as gr
import random

def play_turn(guess, round_num):
    target = random.randint(1, 5)
    result = "Win! 🎉" if int(guess) == target else f"Miss! Target was {target}"
    return round_num + 1, f"Round {round_num}: {result}"

with gr.Blocks() as demo:
    gr.Markdown("### Guessing Game")
    round_state = gr.State(1)
    
    guess_num = gr.Slider(1, 5, value=3, step=1, label="Guess Number (1-5)")
    play_btn = gr.Button("Play Round")
    status = gr.Textbox(label="Game Log")
    
    play_btn.click(play_turn, inputs=[guess_num, round_state], outputs=[round_state, status])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Guessing Game

Guess Number (1-5): [----●----]
Round 2: Win! 🎉
Example 8: Multi-File Batch Processing Queue State
Accumulates multiple uploaded files into a persistent batch list for sequential processing.
Python (state_ex8.py)
import gradio as gr

fn = lambda file, batch: (batch + [file.name], f"Queued Files Count: {len(batch) + 1}") if file else (batch, "No file")

with gr.Blocks() as demo:
    gr.Markdown("### Batch File Queue")
    batch_state = gr.State([])
    
    f_in = gr.File(label="Upload Document")
    log_out = gr.Textbox(label="Queue Status")
    
    f_in.upload(fn, inputs=[f_in, batch_state], outputs=[batch_state, log_out])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Batch File Queue

Drag and Drop Files Here
Queued Files Count: 3
Example 9: User Authentication Session Token State
Stores login session validation tokens securely in `gr.State` to restrict dashboard access.
Python (state_ex9.py)
import gradio as gr

def login(user, pwd):
    if user == "admin" and pwd == "secret":
        return True, "Login Successful! Welcome Admin."
    return False, "Invalid Credentials."

with gr.Blocks() as demo:
    gr.Markdown("### Secure Portal Login")
    auth_state = gr.State(False)
    
    u_box = gr.Textbox(label="Username")
    p_box = gr.Textbox(label="Password", type="password")
    login_btn = gr.Button("Login")
    msg = gr.Textbox(label="Authentication Status")
    
    login_btn.click(login, inputs=[u_box, p_box], outputs=[auth_state, msg])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Secure Portal Login

Username: admin
Password: ********
Login Successful! Welcome Admin.
Example 10: Dynamic Poll Voting Counter & Percentage Calculator
Records individual votes into a state-managed dictionary and computes live response percentages.
Python (state_ex10.py)
import gradio as gr

def vote(option, votes):
    votes[option] = votes.get(option, 0) + 1
    total = sum(votes.values())
    summary = "\n".join([f"{k}: {v} votes ({(v/total)*100:.1f}%)" for k, v in votes.items()])
    return votes, summary

with gr.Blocks() as demo:
    gr.Markdown("### Live Opinion Poll")
    poll_state = gr.State({})
    
    choice = gr.Radio(["Python", "JavaScript", "Rust"], label="Favorite Language")
    vote_btn = gr.Button("Cast Vote")
    results = gr.Textbox(label="Poll Results", lines=4)
    
    vote_btn.click(vote, inputs=[choice, poll_state], outputs=[poll_state, results])

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Live Opinion Poll

◉ Python ○ JavaScript ○ Rust
Python: 12 votes (60.0%)
JavaScript: 8 votes (40.0%)