Testing Render vs Effect Approaches
You'll learn: How to compare render-time computation versus useEffect synchronization by looking at code complexity and potential for bugs.
When you're deciding between computing a value during render or using useEffect to synchronize it, testing helps reveal which approach is simpler and safer.
The Complexity Test
Render-time computation:
function FilteredList({ items, filter }) {
const filtered = items.filter(item => item.type === filter);
return <ul>{filtered.map(...)}</ul>;
}
To test: render with props, assert output. Done.
Effect-based approach:
function FilteredList({ items, filter }) {
const [filtered, setFiltered] = useState([]);
useEffect(() => {
setFiltered(items.filter(item => item.type === filter));
}, [items, filter]);
return <ul>{filtered.map(...)}</ul>;
}
To test: render, wait for effect, assert output. More steps, more failure points.
The Bug Surface Area
The effect version introduces bugs that don't exist in direct computation:
- Missing dependency → stale data
- Wrong initial state → flash of incorrect content
- Race condition if dependencies change rapidly
- Extra render cycle → performance cost
The render version has none of these concerns. The filtered value is always correct for the current props—no synchronization needed.
The Analogy
Think of it like cooking: you could dice onions when you need them (render-time), or you could set up a system that watches your recipe and dices onions in response to changes (effect). The second approach needs more coordination, more can go wrong, and you still end up with diced onions—just with extra steps.
Testing in Practice
If your test needs waitFor, act, or dependency array verification to work correctly, that's a smell that the effect might be unnecessary.
Key Takeaway: Simpler code is easier to test. If you can compute a value during render, tests for that approach will be more straightforward and the code will have fewer potential bugs than an effect-based synchronization.