Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท State and Events

Session State with gr.State

Keep data between Gradio events safely: why globals are shared between all users, how gr.State gives each session its own value, and when to use BrowserState or a database.

A Gradio function is called fresh on every event, so it forgets everything when it returns. Yet apps need memory: a shopping list, the previous chat turns, a counter, a loaded model's settings. There are three kinds of state, and mixing them up is the number one cause of "my app shows another user's data" bugs. This lesson explains them with the safe default, gr.State. Gradio code is read-only; stand-ins let you reproduce both the bug and the fix.

Three kinds of state

Kind Lives Visible to Use for
Global (module variables) Server process Every user Loaded models, read-only config, caches
Session (gr.State) Server memory, per browser tab session One user (one page load) Per-user working data
Browser (gr.BrowserState, localStorage) The user's browser One user, survives reload Preferences, saved drafts

Anything else (a database, a file, a cache) is external state you manage yourself.

gr.State in practice

Python
import gradio as gr

def add_item(items, text):
    if text:
        items = items + [text]
    return items, "\n".join(items), ""

with gr.Blocks() as demo:
    items = gr.State([])                     # starts as an empty list
    new = gr.Textbox(label="New item")
    shown = gr.Textbox(label="Your list", interactive=False)
    add = gr.Button("Add")
    add.click(add_item, [items, new], [items, shown, new])

gr.State is not drawn on the page; it is an invisible component that holds a Python object on the server for that browser session. It is used as both input and output of events. Clicking Add passes the current list in, returns the new list as the first output (which updates the state), the formatted text for the visible box, and an empty string to clear the input. Opening the page in a second tab starts with a fresh []; the lists of different users never mix.

Points to remember:

  • The initial value is copied for each session, so a mutable default like gr.State([]) is safe in Gradio (unlike a Python default argument).
  • State values must be deep-copyable and live in memory. They are not serialized to the browser, so they can be arbitrary Python objects (a model handle, a database connection factory), but they disappear when the session ends (the tab is closed and a timeout passes; configurable with gr.State(time_to_live=...) in newer versions).
  • Return a new object (items + [text]) rather than mutating in place, so changes are detected reliably and any @gr.render depending on the state refreshes.
  • Large state (images, big arrays) uses server memory for every active session. Keep it small, or store a key and keep the data in a cache.

The shared-global bug

Compare what happens with a module-level variable:

Python
counter = 0

def click():
    global counter
    counter += 1
    return counter

Every visitor increments the same counter. If Alice clicks twice and Bob once, Bob's next click shows 4. This is correct for something like "total visits" and wrong for per-user data. Because Gradio runs functions in threads, a global that is modified can also be subject to race conditions (two clicks interleaving); protect shared mutable globals with a threading.Lock.

Choosing the right place

flowchart TD
    Q["Whose data is it?"] -->|"Everyone's, read-only"| G["Global variable or cache"]
    Q -->|"One user, this visit"| S["gr.State"]
    Q -->|"One user, across visits"| B["gr.BrowserState"]
    Q -->|"Must survive restarts<br/>or be shared"| D["Database or file"]

Pick the smallest scope that works.

BrowserState and persistence

gr.BrowserState stores a JSON-serializable value in the browser's localStorage, so it survives page reloads and server restarts:

Python
with gr.Blocks() as demo:
    saved_name = gr.BrowserState("")
    name = gr.Textbox(label="Name")

    @demo.load(inputs=saved_name, outputs=name)
    def restore(value):
        return value

    name.change(lambda n: n, name, saved_name)

Reloading the page refills the name box. Remember this value is in the user's browser: they can read and edit it, and clearing site data erases it. Never store secrets in it, and validate it like any user input.

For data that must be kept (accounts, saved projects), use a database keyed by a user identifier. Gradio gives you gr.Request in a function (add a parameter request: gr.Request) to read headers, the client's IP address and the session hash (request.session_hash), and gr.OAuthProfile for logged-in users on Hugging Face Spaces.

Stand-in 1: the shared-global bug

This stand-in is our own code. Two simulated users share one process, the way real Gradio users do.

Python Stand-in: global versus per-session counters

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.

Bob's first click shows 3 with the global and 1 with session state. Real gr.State is this dictionary, keyed by the session hash, managed for you.

Stand-in 2: a State-like store with a copied default

Python Stand-in: initial value copied per session

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.

Because each session gets a copy of the initial value, gr.State([]) is safe even though a mutable default is dangerous in ordinary Python function signatures.

Checklist before shipping

  • Search your code for global and module-level lists or dicts that change at runtime.
  • Put per-user data in gr.State, and shared read-only data in globals.
  • Keep a lock around shared mutable data.
  • Never store secrets in BrowserState.
  • Test with two browser windows (or a private window) to catch sharing bugs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who sees a module-level counter that your function increments?

    All users share one Python process, so globals are shared state.
  2. 2. What is gr.State?

    It holds a value on the server for one browser session and is passed as input and output of events.
  3. 3. Why return a new list instead of mutating the state list in place?

    A new object makes the change visible to the framework.
  4. 4. Which state survives a page reload and a server restart?

    BrowserState uses the browser's localStorage. It is user-controlled, so never put secrets in it.

Summary

  • Globals are shared by all users; use them only for read-only data and protect writes with a lock.
  • gr.State keeps per-session Python objects, copied from the initial value.
  • Return new objects to update state; keep it small.
  • gr.BrowserState persists in the browser; use a database for durable server data.

Next: Generators and Streaming Output