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.
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:
With State Variables
When used with state variables, memoized components will only re-render when the specific state variables they depend on change:
Advanced Event Handler Example
You can also pass arguments to event handlers in memoized components:
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