Performance: Conditional styling patterns
MEDIUM IMPACT
Conditional styling affects page rendering speed and visual stability by controlling how and when styles are applied during component updates.
import clsx from 'clsx'; const MyComponent = ({ isActive }) => { return <div className={clsx('base-style', { 'active-style': isActive })}>Hello</div>; }; // CSS: // .base-style { color: blue; font-weight: normal; } // .active-style { color: red; font-weight: bold; }
const MyComponent = ({ isActive }) => { return <div style={{ color: isActive ? 'red' : 'blue', fontWeight: isActive ? 'bold' : 'normal' }}>Hello</div>; };
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline style objects recreated each render | No extra DOM nodes | Multiple reflows per render | High paint cost due to style recalculations | [X] Bad |
| Conditional CSS class toggling | No extra DOM nodes | Single reflow on class change | Low paint cost leveraging browser optimizations | [OK] Good |