Decentralized event handlers allow you to define event handlers outside of state classes, providing more flexible code organization. This feature was introduced in Reflex v0.7.10 and enables a more modular approach to event handling.
With decentralized event handlers, you can:
- Organize event handlers by feature rather than by state class
- Separate UI logic from state management
- Create more maintainable and scalable applications
To create a decentralized event handler, use the @rx.event
decorator on a function that takes a state instance as its first parameter:
Count: 0
In this example:
- We define a
MyState
class with acount
variable - We create a decentralized event handler
increment
that takes aMyState
instance as its first parameter - We use the event handler in buttons, passing different amounts to increment by
Here's a comparison between traditional event handlers defined within state classes and decentralized event handlers:
Key differences:
- Traditional event handlers use
self
to reference the state instance - Decentralized event handlers explicitly take a state instance as the first parameter
- Both approaches use the same syntax for triggering events in components
- Both can be decorated with
@rx.event
respectively
Decentralized event handlers are particularly useful in these scenarios:
- Large applications with many event handlers that benefit from better organization
- Feature-based organization where you want to group related event handlers together
- Separation of concerns when you want to keep state definitions clean and focused
Always use proper type annotations for your state parameter and any additional parameters:
Follow these naming conventions for clarity:
- Use descriptive names that indicate the action being performed
- Use the state class name as the type annotation for the first parameter
- Name the state parameter consistently across your codebase (e.g., always use
state
or the first letter of the state class)
Consider these approaches for organizing decentralized event handlers:
- Group related event handlers in the same file
- Place event handlers near the state classes they modify
- For larger applications, create a dedicated
events
directory with files organized by feature
Decentralized event handlers work seamlessly with other Reflex event features: