Events are how Reflex responds to user interactions like clicking a button, submitting a form, or hovering over an element. In Reflex, events trigger Event Handlers in your State class.
An event handler is a method in your state class that logic.
class CounterState(rx.State):
count: int = 0
def increment(self):
self.count += 1
You hook this up in your UI using component props:
rx.el.button("Add", on_click=CounterState.increment)
If an event handler performs a long-running task (like an API call), it should be async. Reflex also allows you to yield actions to update the UI progressively.
class SearchState(rx.State):
results: list[str] = []
loading: bool = False
async def run_search(self, query: str):
self.loading = True
yield # Update UI to show loading spinner
# Simulate API call
await asyncio.sleep(2)
self.results = ["Result 1", "Result 2"]
self.loading = False
You can trigger multiple events from a single interaction by passing a list to the event prop.
rx.el.button(
"Save",
on_click=[
State.save_data,
rx.toast("Data Saved!"),
rx.redirect("/dashboard")
]
)
Triggers than can be attached to Reflex components:
Reflex provides built-in "Special Actions" that can be triggered from handlers: