Inline styles in React (or other frameworks) can impact performance and re-renders differently than CSS classes. Here’s what you need to know:
Key Differences
- Re-render Behavior:
- Inline styles are recalculated and reapplied on every render
- CSS classes remain static and are simply toggled/added/removed
- Performance Impact:
- Inline styles cause more DOM operations since styles are rewritten
- CSS classes have better performance for frequent updates
When Inline Styles Trigger Re-renders
// This will cause style recalculation on every parent re-render
function Component() {
return <div style={{ color: 'red', padding: '10px' }}>Content</div>;
}
Better Approaches
- For dynamic styles:
function Component({ isActive }) {
// Combine static classes with dynamic inline styles when needed
return (
<div
className="base-style"
style={{ color: isActive ? 'red' : 'black' }}
>
Content
</div>
);
}
- CSS-in-JS alternatives (better for performance):
import styled from 'styled-components';
const StyledDiv = styled.div`
color: ${props => props.isActive ? 'red' : 'black'};
padding: 10px;
`;
function Component({ isActive }) {
return <StyledDiv isActive={isActive}>Content</StyledDiv>;
}
Recommendations
- Use CSS classes for static styles
- Reserve inline styles for truly dynamic styles that change frequently
- Consider CSS-in-JS solutions for the best balance of dynamic styling and performance
- Avoid creating new style objects in render methods (they’ll trigger re-renders)
Inline styles aren’t inherently bad, but they should be used judiciously to avoid unnecessary performance overhead.