Memo
The memo decorator is used to optimize component rendering by memoizing components that don't need to be re-rendered. This is particularly useful for expensive components that depend on specific props and don't need to be re-rendered when other state changes in your application.
Requirements
When using rx.memo, you must follow these requirements:
- Type all arguments: All arguments to a memoized component must have type annotations.
- Use keyword arguments: When calling a memoized component, you must use keyword arguments (not positional arguments).
Basic Usage
When you wrap a component function with @rx.memo, the component will only re-render when its props change. This helps improve performance by preventing unnecessary re-renders.
ExpandCollapse
In this example, the expensive_component will only re-render when the label prop changes, not when the count state changes.
With Event Handlers
You can also use rx.memo with components that have event handlers:
ExpandCollapse
With State Variables
When used with state variables, memoized components will only re-render when the specific state variables they depend on change:
ExpandCollapse
Advanced Event Handler Example
You can also pass arguments to event handlers in memoized components:
ExpandCollapse
Performance Considerations
Use rx.memo for:
- Components with expensive rendering logic
- Components that render the same result given the same props
- Components that re-render too often due to parent component updates
Avoid using rx.memo for:
- Simple components where the memoization overhead might exceed the performance gain
- Components that almost always receive different props on re-render
API Reference
rx.memo
Decorates a function that returns a Reflex component so it can be reused as a memoized component. The function arguments must be type annotated, and memoized components should be called with keyword arguments.