What is state?
In Gradio, “state” refers to data that persists across multiple function calls within a user session. Without state, each interaction is independent - the application has no memory of previous inputs or outputs. State in Gradio is:- Session-specific: Each user has their own isolated state
- Temporary: State resets when the user refreshes the page or their session expires
- Invisible: State components don’t appear in the UI
- Flexible: Can store any Python object (lists, dicts, custom objects)
The State component
The simplest way to manage state is with theState component:
- Initialize state with a default value:
gr.State(value=0) - Include state in both
inputsandoutputsto update it - Return the updated state from your function
Common state patterns
Accumulating chat history
Maintain conversation context in a chatbot:Multi-step workflows
Collect information across multiple interactions:Maintaining counters
Track user actions or iterations:State in Interface
When usinggr.Interface, you can use the special "state" string shortcut:
Complex state objects
State can hold any Python object, including custom classes:State vs component values
When to use State
Usegr.State when you need to:
- Store data that shouldn’t be visible to users
- Maintain large data structures (models, datasets)
- Track internal application state
- Keep intermediate computation results
When to use regular components
Use regular components as “state” when:- Users need to see the persisted value
- The state is simple and fits a component type
- You want users to potentially edit the state
Initializing state
Default values
Set initial state when creating the component:Dynamic initialization
Initialize state based on computations:Clearing state
Reset state to initial values:ClearButton:
State limitations
Session isolation
Each user session has independent state:If you need to share data across all users, use global Python variables or a database. However, be careful with thread safety!
Not persistent across refreshes
State resets when the page refreshes:Memory considerations
State is stored in server memory:Advanced patterns
Conditional state updates
Update state only under certain conditions:State with multiple functions
Pass state through a chain of operations:See also
- Components - State is a special component
- Events - How to update state via events
- Blocks - Using state in custom layouts
- ChatInterface - Built-in chat history state management