Pure Component
Problem
Components re-render unpredictably with the same properties, making performance optimization impossible and introducing subtle bugs. Testing becomes unreliable because components produce different output or trigger unexpected side effects even when given identical inputs.
Solution
Create components that render the same output for the same inputs with no side effects. This makes them predictable, testable, and eligible for performance optimizations.
Example
This example demonstrates a pure component that produces consistent output for the same inputs and only re-renders when its observed attributes actually change.
// Framework-agnostic pure component
class Greeting extends HTMLElement {
static get observedAttributes() {
// Declare which attributes trigger re-renders
return ['name'];
}
attributeChangedCallback(name, oldValue, newValue) {
// Only re-render if value actually changed (optimization)
if (name === 'name' && newValue !== oldValue) {
this.render();
}
}
render() {
// Pure rendering - same input always produces same output
const name = this.getAttribute('name');
this.innerHTML = `<h1>Hello, ${name}!</h1>`;
}
}
// Same attributes = same output (pure function behavior)
customElements.define('greeting-component', Greeting);
Benefits
- Makes components predictable and easier to reason about.
- Enables performance optimizations by skipping unnecessary re-renders.
- Simplifies testing since output is deterministic based on inputs.
- Makes components safer to reuse in different contexts.
Tradeoffs
- Cannot perform side effects like API calls directly in render method.
- Requires separating side effects from rendering logic.
- Memoization adds comparison overhead that may not always be beneficial.
- May be over-optimization for components that rarely re-render.