Chapter 4 of 8
Course Progress0 of 8 completed (0%)

Modern Full-Stack & React Internals · Chapter 4 · ~15 min · Intermediate

The Lifecycle of an Effect & Re-render Cycles

Demystify useEffect and re-renders: dependency array reference equality, effect synchronization vs event handlers, cleanups, StrictMode double-invocations, and useRef for non-rendering mutability.

  • Understand how dependency arrays evaluate reference equality (Object.is)
  • Master effect cleanup functions to prevent memory leaks
  • Prevent infinite re-render loops caused by inline object dependencies
  • Use useRef to store mutable values without triggering re-renders

The Lifecycle of an Effect & Re-render Cycles: learn it visually

Demystify useEffect and re-renders: dependency array reference equality, effect synchronization vs event handlers, cleanups, StrictMode double-invocations, and useRef for non-rendering mutability.

The Lifecycle of an Effect & Re-render CyclesDemystify useEffect and re-renders: dependency array reference equality, effect synchronization vs event handlers, cleanups, StrictMode double-invocations, and useRef for non-rendering mutability.UNDERSTANDRender componentFOLLOW THE FLOWRun the effectAPPLY ITRender againThe Lifecycle of an Effect & Re-render CyclesDemystify useEffect and re-renders: dependency array reference equality, effect synchronization vs event handlers, cleanups, StrictMode double-invocations, and useRef for non-rendering mutability.UNDERSTANDRender componentFOLLOW THE FLOWRun the effectAPPLY ITRender again

1Effects: Synchronization, Not Lifecycle Hooks

In React, there are two primary kinds of logic inside components:

  1. Rendering code: Takes props and state, returns JSX. Must be pure (no side effects, no mutations).
  2. Event handlers: Nested functions like handleClick that perform side effects (sending a form, showing an alert) in response to a specific user action.

What happens when a side effect must run not because of a specific button click, but because the component is displayed on screen or its current state changed? That is what Effects are for: synchronizing your React component to an external system (a browser API, a timer, a chart library, or a network socket).

Wrong idea: Effects are lifecycle hooks (componentDidMount / Unmount)

componentDidMount() { connect(roomId); }
componentDidUpdate() { reconnect(); }
Splits one synchronization into disconnected methods

Thinking in terms of 'when the component mounts, run this; when it unmounts, run that' like legacy class lifecycle methods.

Real system: Effects synchronize external systems to state

useEffect(() => { connect(roomId); return () => disconnect(); }, [roomId]);
Setup & cleanup self-contained · synchronizes continuously

An effect is a continuous synchronization function that runs AFTER render whenever dependencies change, matching external systems to current UI state.

2The Dependency Array & The Object.is Trap

The second argument to useEffect is the dependency array. React uses it to decide whether to re-run the effect:

useEffect(() => {
  // Runs after EVERY render:
});

useEffect(() => {
  // Runs ONLY ONCE after initial mount:
}, []);

useEffect(() => {
  // Runs after mount AND whenever 'roomId' changes:
}, [roomId]);

Crucial Insight: React compares dependencies using JavaScript's Object.is(prevDep, nextDep). Primitives (string, number, boolean) are compared by value. Objects, arrays, and functions are compared by memory reference:

// DANGEROUS: Infinite Re-render Loop!
function ChatRoom({ roomId }) {
  // Fresh object literal created on EVERY single render!
  const options = { server: "https://api.coderhub.com", room: roomId };

  useEffect(() => {
    connect(options);
  }, [options]); // Object.is(oldOptions, newOptions) is ALWAYS false!
}

3The Execution Pipeline: Render, Paint, Cleanup, Setup

A common misconception is that cleanup functions only run when the component unmounts. In reality, the cleanup function runs before EVERY subsequent effect setup:

useEffect(() => {
  const connection = createConnection(roomId);
  connection.connect();

  // CLEANUP FUNCTION:
  return () => {
    connection.disconnect();
  };
}, [roomId]);

If the user switches from Room #101 to Room #202:

  1. React renders the component with roomId=202.
  2. React paints the new UI on the screen.
  3. React runs the cleanup for Room #101 (disconnect()).
  4. React runs the setup for Room #202 (connect()).

Predict first

Why does React 18 StrictMode mount, unmount, and re-mount every component once on initial page load in development?

4Stale Closures & Functional State Updaters

In JavaScript, functions "close over" the variables that were in scope when the function was created. If an effect schedules a timer or callback with an empty dependency array, it captures the initial state value forever:

// BROKEN: Stale Closure Trap
useEffect(() => {
  const timer = setInterval(() => {
    // 'count' is forever frozen at 0 from render #1!
    setCount(count + 1); // Sets state to 0 + 1 = 1 every second!
  }, 1000);

  return () => clearInterval(timer);
}, []); // Empty deps captures count = 0

// FIXED: Functional State Updater
useEffect(() => {
  const timer = setInterval(() => {
    // 'c' is the guaranteed latest state in React Fiber!
    setCount((c) => c + 1);
  }, 1000);

  return () => clearInterval(timer);
}, []); // Safe! No dependency on external 'count' variable.

5useRef: Mutable Storage Without Re-renders

When you need to store a piece of information that survives across renders, but changing it should not trigger a UI redraw, use useRef:

// Storing timer IDs, previous values, or DOM nodes:
const timerRef = useRef<number | null>(null);

function startTimer() {
  timerRef.current = window.setInterval(tick, 1000);
}

function stopTimer() {
  if (timerRef.current !== null) {
    clearInterval(timerRef.current);
    timerRef.current = null;
  }
}

6Hands-On: Effect Lifecycle & Re-render Timeline

Observe how React sequences render, paint, cleanup, and setup in real time. Switch dependencies, trigger identical re-renders, or simulate unmounts to inspect the chronological event pipeline:

Live Effect Lifecycle & Re-render Timeline

Render Cycle #1 · Room #101

Trigger Component Lifecycle Actions:

Sequential Execution Pipeline:Render → Paint → Cleanup → Setup
RENDER
1. Render Phase (Render #1)
0.0ms

Component function executes: Virtual DOM computed with userId=101.

PAINT
2. Commit & DOM Paint
1.2ms

React mutates the DOM tree. User sees updated UI on screen.

SETUP
3. Effect Setup (Mount)
2.4ms

useEffect callback fires: Opened WebSocket connection to chat room #101.

7Bug Hunt: Fix the Leaking Interval & Stale Closure

A teammate built a live stopwatch, but when you hit Resume and Pause, timers stack up in the background and the clock freezes at 1 second! Fix the stale closure and missing cleanup below:

Stale Closure & Missing Cleanup Bug Hunt
TypeScript JSX

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Use a functional state updater: setSeconds(s => s + 1) to avoid capturing stale values.
  • Return a cleanup function from the effect: return () => clearInterval(intervalId);.

8Chapter Knowledge Challenge

Test your understanding of effects, dependency equality, and cleanups:

Concept Check 1 of 3
1

When does the cleanup function returned by useEffect execute?

Concept Check 2 of 3
2

Why does useEffect(fn, [{ id: 1 }]) cause an infinite re-render loop if the effect updates state?

Concept Check 3 of 3
3

How does modifying a useRef object (ref.current = value) differ from useState (setState(value))?

9Recap & Architectural Takeaways

  • Synchronization over Lifecycles: Think of effects as syncing your component with external systems, not as mount/unmount triggers.
  • Reference Equality: Dependency arrays check dependencies with Object.is. Keep dependencies primitive or memoized.
  • Always Clean Up: Always return cleanup functions for timers, subscriptions, event listeners, and WebSockets.
  • Functional State Updaters: Use setState(prev => prev + 1) to safely update state inside intervals without stale closure bugs.

Ready to dive into the Fiber engine and Reconciliation in Chapter 5?

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us