Topic 25 of 54
Modern View
Overview
Historically (in Class components), React developers thought about components in terms of 'Mounting', 'Updating', and 'Unmounting'. In modern Functional React, we think differently. A component simply renders. During or after that render, it might need to synchronize with an external system (like a database, a subscription, or the browser DOM). We call this synchronization a 'Side Effect'.
Syntax
Always remember: Effects run *after* the render is committed to the screen. They are an 'escape hatch' to step outside of React's pure rendering cycle.
The Mental Model
jsx
// 1. Render Phase (Pure):
// React calculates what the UI should look like based on State and Props.
// DO NOT mutate variables, call APIs, or touch the DOM here.
// 2. Commit Phase:
// React applies the calculated changes to the Real DOM.
// 3. Effect Phase:
// React runs your 'Side Effects' (like fetching data) AFTER the screen has updated.Common Pitfalls
- Using `useEffect` to transform data before rendering. If data can be derived from props or state during the render, calculate it directly! Effects should be reserved for interacting with *external* systems.
Interview Tips
- If asked about the lifecycle, mention that hooks shifted the paradigm from 'lifecycle methods' (componentDidMount, etc.) to 'synchronizing state with external systems' via `useEffect`.
Real-World Example
You should not use Effects for things that can be calculated during render.
example
jsx
// ❌ BAD: Using an effect to derive data (causes an extra, slow re-render)
function BadCart({ items }) {
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);
}
// ✅ GOOD: Calculate it directly during the render phase
function GoodCart({ items }) {
const total = items.reduce((sum, item) => sum + item.price, 0);
}