Extracting Style Objects
You'll learn how to avoid recreating style objects on every render by extracting them as constants, and when this optimization actually matters.
The Problem with Inline Style Objects
Every time you write style={{ color: 'blue', fontSize: 16 }} directly in your JSX, React creates a new object on every render. Since JavaScript objects are compared by reference, this makes React think the style has changed even when the values are identical.
// ❌ New object every render
function Button() {
return <button style={{ padding: '10px', backgroundColor: 'blue' }}>Click</button>;
}
Extract to a Constant
Move the style object outside the component, or declare it once inside. React will now reference the same object across renders:
// ✅ Same object reference every time
const buttonStyle = { padding: '10px', backgroundColor: 'blue' };
function Button() {
return <button style={buttonStyle}>Click</button>;
}
When Does This Actually Matter?
Honestly? Usually not much. Modern React is fast, and creating small objects is cheap. Extract styles when:
- You're optimizing a component that renders thousands of times (lists, animations)
- You're using
React.memoand want to prevent unnecessary re-renders - The style object is large or computed
Don't bother extracting if:
- Your component rarely re-renders
- You're doing premature optimization without measuring
- The style values depend on props or state anyway
Think of it like reusing a coffee mug versus grabbing a new one each time—technically more efficient, but only worth the effort if you're making coffee all day long.
Key Takeaway: Extract inline style objects to constants when you need stable references for performance-sensitive components, but don't stress about it for typical UI code—the performance gain is usually negligible.