State mixins allow you to define shared functionality that can be reused across multiple State classes. This is useful for creating reusable components, shared business logic, or common state patterns.
A state mixin is a State class marked with mixin=True
that cannot be instantiated directly but can be inherited by other State classes. Mixins provide a way to share:
- Base variables
- Computed variables
- Event handlers
- Backend variables
To create a state mixin, inherit from rx.State
and pass mixin=True
:
App
Count: 0
In this example, MyState
automatically inherits the count
variable, count_display
computed variable, and increment
event handler from CounterMixin
.
You can inherit from multiple mixins to combine different pieces of functionality:
Multi-Mixin App
Count: 0
Last updated:
No logs yet
Mixins can also include backend variables (prefixed with _
) that are not sent to the client:
User Management
User count: 0
Backend variables are useful for storing sensitive data, database connections, or other server-side state that shouldn't be exposed to the client.
Computed variables in mixins work the same as in regular State classes:
Product: Widget
Price: $0.00
Positive: false
Mixins can inherit from other mixins to create hierarchical functionality:
Base: base
Extended: extended
Combined: base-extended
Final: final
This pattern allows you to build complex functionality by composing simpler mixins.
State mixins are particularly useful for:
- Form Validation: Shared validation logic across forms
- UI State Management: Common modal, loading, or notification patterns
- Logging: Centralized logging and debugging
- API Integration: Shared HTTP client functionality
- Data Formatting: Consistent data presentation across components
Contact Form
By using state mixins, you can create modular, reusable state logic that keeps your application organized and reduces code duplication.