gradio · difficulty ◆◆
gradio State — one Python object per visitor, kept off the browser
gr.State is the component that renders nothing and remembers everything — and the copy your visitor gets is not the copy you passed in.
Before gr.State, the trick was a hidden Textbox holding a JSON blob — which meant the visitor's browser could read your cart, rewrite it, and hand it back.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ gr.State()- 3.2
- Blocks State shipped
- 4
- Constructor params
- 10,000
- Sessions held in RAM
- 1 s
- Expiry sweep interval
2022-08-31 — `gr.Variable` renamed to `gr.State`; the alias disappeared in 4.0.0
value, render, time_to_live, delete_callback — counted from the 6.31.0 signature
default `state_session_capacity`; the 10,001st evicts the least recently used session
`route_utils._delete_state` loops on `delete_all_expired_state()` every second
What it does
`gr.State(value=0)` creates a component with no DOM node at all. You pass it into listeners exactly like a Textbox — as an input to read, as an output to write — and Gradio keeps the value in a server-side map keyed by the visitor's session, not in the page. The 6.31.0 signature has four parameters: `value`, `render`, and the keyword-only `time_to_live` and `delete_callback`. The initial value is `deepcopy`-ed at construction and again per session, so two tabs never share a list. Because `get_config()` deletes the `value` key and the class sets `skip_api = True`, the browser and the API client both see a state that exists but holds nothing they can read.
Why it matters
Every demo eventually needs something a widget is a bad home for: a loaded model, an open database connection, a cart, the twelve turns of a conversation, a 200MB dataframe you already filtered. Parking those in a hidden Textbox means serialising them into the page, where the visitor can edit them and where a 5MB JSON blob becomes a request header. State keeps the object in the Python process and sends one session id. It is also the difference between a demo that reloads the model on every click and one that loads it once per visitor — measured below at 1.20s for the first click and 0.00s for the second.
Example
$ import time
import gradio as gr
def load_embedding_index():
"""Stands in for a real model/index load — 1.2s of work, once per session."""
time.sleep(1.2)
return {"docs": 1204, "dim": 384}
def answer(question, index):
if index is None: # first call in this browser session
t0 = time.perf_counter()
index = load_embedding_index()
print(f"built session index in {time.perf_counter() - t0:.2f}s")
else:
print("reused the index already held in this session")
return index, f"{index['docs']} docs · {index['dim']}-d · asked: {question}"
with gr.Blocks(title="Docs Q&A") as demo:
index = gr.State(value=None) # per-session, never sent to the browser
q = gr.Textbox(label="Question", placeholder="How do refunds work?")
run = gr.Button("Ask", variant="primary")
out = gr.Markdown()
run.click(answer, [q, index], [index, out])
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
What renders: one Textbox labelled 'Question', a primary 'Ask' button, and an empty Markdown. There is no widget for the State — it occupies no space in the DOM, and in /config it serialises as `{type: "state", props: {time_to_live: None, delete_callback: "<function default_delete_callback ...>", name: "state"}, skip_api: true}` with no `value` key at all.
Three calls through gradio_client, which mints a fresh session per client object:
CALL1 1204 docs · 384-d · asked: How do refunds work?
CALL2 1204 docs · 384-d · asked: And for enterprise?
C2 1204 docs · 384-d · asked: fresh tab
Server console, in order:
built session index in 1.20s
reused the index already held in this session
built session index in 1.20s
The first click paid 1.20s; the second click on the same session paid nothing, because `index` was the same dict object coming back out of state. The third line is a second client — a different visitor — and it built its own copy.The `None` default is the cheapest possible flag for 'nothing built yet'. Pass the state as both an input and an output, otherwise you get back an index that the next click won't see.
$ import gradio as gr
PLANS = ["starter", "team", "enterprise"]
def record(name, plan, answers, step):
answers = dict(answers or {})
if name:
answers["name"] = name
if plan:
answers["plan"] = plan
step = min(step + 1, 3)
summary = " · ".join(f"{k}={v}" for k, v in answers.items()) or "(empty)"
return answers, step, f"step {step}/3 — {summary}"
def back(answers, step):
return max(step - 1, 1), f"step {max(step - 1, 1)}/3 — {answers}"
with gr.Blocks(title="Signup") as demo:
answers = gr.State({})
step = gr.State(1)
with gr.Group():
name = gr.Textbox(label="Your name")
plan = gr.Radio(PLANS, label="Plan")
nxt = gr.Button("Next", variant="primary")
prev = gr.Button("Back")
status = gr.Markdown("step 1/3 — (empty)")
nxt.click(record, [name, plan, answers, step], [answers, step, status])
prev.click(back, [answers, step], [step, status])
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
What renders: a Group holding a 'Your name' Textbox and a 'Plan' Radio with three options (starter, team, enterprise), then a primary 'Next' and a plain 'Back' button, then the Markdown line 'step 1/3 — (empty)'. Two of the four values each listener moves around — `answers` and `step` — have no widget behind them.
Driving the same two endpoints through gradio_client, on one session:
STEP1 step 2/3 — name=Ada · plan=team
STEP2 step 3/3 — name=Ada · plan=enterprise
BACK step 2/3 — {'name': 'Ada', 'plan': 'enterprise'}
`view_api` for this app reported `/record` with parameters `name: str, plan: Literal['starter','team','enterprise']` and `/back` with no parameters at all — the states were silently dropped from both signatures and from the returned values. The response contained only the Markdown string; the dict and the step counter stayed on the server.A wizard is the honest use for State: the intermediate answers are real data, but they belong in Python, not in a hidden field. Note the API never saw them — that is skip_api doing its job, and it means the browser cannot forge a `name=admin`.
$ import sqlite3
import gradio as gr
def connect(_state):
conn = sqlite3.connect(":memory:") # not picklable, not JSON, not a Gradio type
conn.execute("create table orders(id integer, total real)")
conn.executemany("insert into orders values (?, ?)",
[(1, 19.9), (2, 45.0), (3, 7.5)])
return conn, "session database opened with 3 orders"
def total(conn):
if conn is None:
return "no database in this session yet — click Open first"
(sum_total,) = conn.execute("select sum(total) from orders").fetchone()
return f"sum(total) = {sum_total:.2f}"
with gr.Blocks(title="Order browser") as demo:
conn = gr.State(value=None)
out = gr.Textbox(label="Result")
gr.Button("Open session database").click(connect, conn, [conn, out])
gr.Button("Total").click(total, conn, out)
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
What renders: two buttons ('Open session database', 'Total') and a read-only-looking 'Result' Textbox. Nothing on screen hints that a live database handle is being passed around.
Same session, in order:
TOTAL BEFORE OPEN no database in this session yet — click Open first
OPEN session database opened with 3 orders
TOTAL sum(total) = 72.40
A second client, never having opened anything:
OTHER SESSION TOTAL no database in this session yet — click Open first
The connection object lived in `StateHolder.session_data[<session>].state_data` for the whole session — sqlite3.Connection has no `__reduce__`, so it could not have been sent to a browser or through a JSON response even if you wanted it to be.This is the sharpest argument for State over a hidden Textbox: the object here is a C-level handle. Nothing serialises it, because nothing has to.
$ import time
import gradio as gr
def open_session(plan):
"""A per-visit resource, e.g. an open file or a paid API session."""
return {"plan": plan, "opened": time.time()}
def close_session(session):
print(f"closing session for {session['plan']} after {time.time() - session['opened']:.0f}s")
def ask(session, question):
if session is None:
return "session expired — click Start a session"
return f"{session['plan']} session answered: {question}"
with gr.Blocks(title="Trial console") as demo:
session = gr.State(value=None, time_to_live=2, delete_callback=close_session)
plan = gr.Radio(["trial", "team"], value="trial", label="Plan")
q = gr.Textbox(label="Question")
out = gr.Markdown()
gr.Button("Start a session").click(open_session, plan, session)
gr.Button("Ask").click(ask, [session, q], out)
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
What renders: a 'Plan' Radio (trial/team), a 'Question' Textbox, two buttons and an empty Markdown. The State has `time_to_live: 2` and a real function in `delete_callback` in /config — both readable from the page, neither a secret.
With `time_to_live=2` the expiry is watchable, same session throughout:
OPEN ()
ASK team session answered: Do trials include SSO?
(3 seconds of sleep)
ASK AFTER 3s session expired — click Start a session
Server console, unprompted by any request:
closing session for team after 2s
The callback fired about two seconds after the value was written, not at the next click — Gradio 6.31 runs a sweeper that calls `state_holder.delete_all_expired_state()` once per second (`route_utils._delete_state`). The expired state then resets to its initial value, which is why `ask` saw `None`.`time_to_live` is seconds since the value was created or last written, not since the page opened. Put it on anything expensive: an LLM session, an open file, a cached dataframe.
Common flags
- gr.State(value={})
- The initial value, `deepcopy`-ed once at construction and again per session. It must be deepcopy-able: a `threading.Lock()` raises "The initial value of `gr.State` must be able to be deepcopied".
- gr.State(value=make_default)
- Pass a callable and Gradio calls it per session instead of copying a literal — verified: two sessions produced `{'session_seen': 2}` and `{'session_seen': 3}` from the same function.
- time_to_live=300
- Since 4.25.0. Seconds until the value resets to its initial value, counted from the last write. A one-second sweeper enforces it even with no traffic.
- delete_callback=close_fn
- Since 4.25.0. Called with the state value when it expires through `time_to_live` or the session is closed — verified on expiry. It does not fire on capacity eviction: with `state_session_capacity=1` the evicted State's callback never ran.
- render=True
- Kept for signature symmetry with every other component; State always renders nothing. Setting it False changes no pixels.
- outputs=[state, ...]
- Always return the state into its own output alongside anything you changed. Leave it out and the *next* listener reads the previous object, or you get Gradio's "didn't return enough output values" error.
- launch(state_session_capacity=10000)
- The LRU cap on sessions, default 10,000. In 6.x it lives on `launch()`, not on `gr.Blocks(...)` — the constructor kwarg raises TypeError.
History
3.2 — the name was already taken
In Gradio 2.x, `gr.State` meant something else: an Interface input with `label`, `default` and `optional`, whose value travelled through the browser between predictions. The Blocks-era per-session object shipped in 3.0.20 as `gr.Variable`. Gradio 3.2 (2022-08-31) renamed it: the wheel's `components.py` has `class State(IOComponent, SimpleSerializable)` with the docstring 'stores session state across runs of the demo by the same user', and `class Variable(State)` carrying 'Variable was renamed to State. This class is kept for backwards compatibility.' The old name survived as an alias through 3.9 and was gone by 4.0.0.
4.25.0 — state finally got a lifetime
Until April 2024 a State lived as long as the process, whether or not anyone was still on the page. Gradio 4.25.0 (2024-04-02) added `time_to_live` and `delete_callback`, started deleting state 60 minutes after a disconnect, and introduced `Blocks.unload()` as the cleanup hook to go with it. The pull request behind it (#7829) is the one that stopped a long-running Space from filling its RAM with abandoned sessions.
Under the hood
Where the value actually lives
`gr.Blocks` owns a `StateHolder`: an `OrderedDict[str, SessionState]` plus a lock, capped at `state_session_capacity`. Browser sessions arrive with short ids like `ab2ygxo3i4m`; gradio_client mints UUIDs like `7305ce0a-0320-4578-8c59-a65893bb758e`. `SessionState.__getitem__` lazily builds each state on first use by `deepcopy`-ing the component's value (or calling it, if it's callable) and caches it in `state_data` keyed by component id — so two tabs get two objects, and mutating a list in place is safe between them. `State.get_config()` deletes the `value` key before serialisation, which is why the page's /config never carries it: I stashed the string `SECRET-TOKEN-42` in a state and grepped both the 27,475-byte page HTML and the /config JSON — absent from both. Writes record a timestamp in `_state_ttl`; the one-second sweeper walks the states, calls `delete_callback(value)` for anything older than `time_to_live`, and drops the entry. Eviction on capacity uses `popitem(last=False)`, so it is oldest-touched-first, not oldest-created-first.
Fun facts
Pros & cons
pros
- + Holds objects no widget can carry — a sqlite connection, a loaded model, a numpy array — because nothing is serialised and nothing crosses the wire.
- + Per-visitor isolation for free: two tabs, two counters, two carts, no global dict and no locking of your own.
- + Invisible to the API surface: `skip_api` keeps state out of `view_api`, out of /docs and out of the returned values, so a client cannot read or forge it.
cons
- − A refresh silently resets the visitor to the initial value while the old session lingers server-side, which reads as a bug to anyone who expects a session cookie.
- − Nothing can read it from JavaScript or from gradio_client, so debugging means printing inside the handler — there is no inspection endpoint.
- − The defaults invite trouble: 10,000 sessions of whatever you stored, and no expiry unless you remember `time_to_live`.
Takeaways
- 1Reach for `gr.State` the moment you would otherwise hide something in a Textbox: history, cart, cache, credentials for a downstream API.
- 2Return the state into its own output every time you change it — a state passed only as an input is read-only.
- 3Two tabs are two visitors. If you want one shared value, that is a module-level object, not a State.
- 4Put `time_to_live` and a `delete_callback` on anything holding a file, a connection or a model; the default is forever.
- 5Never test a `State.change` listener through `gradio_client` — it never fires there, and you will delete working code.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
