Synchronization vs Events

0/2 in this phase0/36 across the roadmap

📖 Concept

One of the biggest hurdles in React is learning when NOT to use useEffect.

Effect vs Event:

  • Events: Logic that should happen because a user clicked a button or submitted a form belongs in an Event Handler, not an effect.
  • Effects: Logic that should happen because a component was displayed or because its props/state changed (synchronizing with an external system) belongs in an Effect.

Avoid Effects for:

  1. Transforming Data: If you can compute state B from state A during render, do it directly. Don't use useEffect to update state B when A changes.
  2. Resetting State: If you need to reset a component when a prop changes, use a key on the component instead of an effect.
  3. Handling User Events: Always prefer event handlers. They are easier to reason about and don't require dependency management.

💻 Code Example

codeTap to expand ⛶
1// ❌ BAD: Using useEffect for data transformation
2function ShoppingCart({ items }) {
3 const [total, setTotal] = useState(0);
4
5 useEffect(() => {
6 setTotal(items.reduce((sum, item) => sum + item.price, 0));
7 }, [items]); // This causes an unnecessary extra render!
8
9 return <div>Total: {total}</div>;
10}
11
12// ✅ GOOD: Compute during render
13function ShoppingCart({ items }) {
14 // If calculation is expensive, use useMemo (covered in Phase 10)
15 const total = items.reduce((sum, item) => sum + item.price, 0);
16
17 return <div>Total: {total}</div>;
18}
19
20// ❌ BAD: Using effect for user action
21function Form() {
22 const [submitted, setSubmitted] = useState(false);
23
24 useEffect(() => {
25 if (submitted) {
26 postData(); // Hard to track 'why' this happened
27 }
28 }, [submitted]);
29
30 return <button onClick={() => setSubmitted(true)}>Submit</button>;
31}
32
33// ✅ GOOD: Use Event Handler
34function Form() {
35 const handleSubmit = () => {
36 postData(); // Direct and easy to follow
37 };
38
39 return <button handleSubmit={handleSubmit}>Submit</button>;
40}

🏋️ Practice Exercise

  1. Review a previous project and find a useEffect that could be replaced by a simple calculation during render.
  2. Refactor a component that uses useEffect to reset state by using the key prop instead.
  3. Create a 'Search' feature where the search only happens when the user clicks 'Submit' (Event) vs when the user stops typing (Effect/Debounce).
  4. Explain to a colleague why 'useEffect' is called an escape hatch.

⚠️ Common Mistakes

  • Using useEffect to update state based on other state (leading to 'render chains').

  • Overusing effects for logic that should be in event handlers.

  • Thinking useEffect is exactly like class lifecycle methods (it's similar but has a different mental model based on synchronization).

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Synchronization vs Events