The State component stores session state that persists across function calls for the same user.
Basic usage
import gradio as gr
def increment(count):
return count + 1, count + 1
with gr.Blocks() as demo:
state = gr.State(value=0)
display = gr.Number(label="Count")
btn = gr.Button("Increment")
btn.click(fn=increment, inputs=state, outputs=[display, state])
demo.launch()
Constructor
Initial state value of any type. The value is deepcopied
time_to_live
int | float | None
default:"None"
Seconds to keep state after creation/update. If None, stored indefinitely
delete_callback
Callable[[Any], None] | None
default:"None"
Function called when state is deleted, receives state value as argument
Events
- change - Triggered when state value changes
Examples
Chat history
import gradio as gr
def chat(message, history):
history = history + [(message, f"Echo: {message}")]
return history, history
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
state = gr.State(value=[])
msg.submit(chat, [msg, state], [chatbot, state])
demo.launch()
With TTL
import gradio as gr
# State expires after 1 hour of inactivity
state = gr.State(value={}, time_to_live=3600)
With cleanup callback
import gradio as gr
def cleanup(value):
print(f"Cleaning up state: {value}")
# Perform cleanup operations
state = gr.State(value={}, delete_callback=cleanup)