Clean Code vs Optimized Code
What you'll learn: How to balance performance optimization with code that's easy to read and maintain.
There's a natural tension in React development: clean, simple code versus heavily optimized code. Clean code is straightforward, easy to understand, and quick to modify. Optimized code uses useMemo and useCallback to squeeze out performance gains, but often at the cost of complexity.
The Core Principle
Start with clean, readable code. Don't add memoization hooks until you've measured a real performance problem. Clean code without memoization is:
- Easier for teammates (and future you) to understand
- Simpler to debug when things go wrong
- Faster to write and modify
- Less prone to bugs from incorrect dependencies
When to Optimize
Only reach for useMemo and useCallback when:
- You've profiled and identified a bottleneck
- Measurements prove the optimization helps
- The performance gain justifies the added complexity
Think of it like home security. You don't install a bank vault door on your bedroom just because it's more secure. You assess the actual risk first. Most bedrooms do fine with a simple lock.
The Default Approach
Write this first:
function UserList({ users }) {
const filtered = users.filter(u => u.active);
return <div>{filtered.map(...)}</div>;
}
Only add useMemo if profiling shows this filtering is actually slow with your real data. The simple version is almost always fine, and it's dramatically easier to read.
Key Takeaway: Default to clean, simple code. Add memoization only when real-world measurements prove you need it—optimization should be the exception, not the rule.