Back to Pathway
hooksintermediate

useEffect

useEffect lets you synchronize a component with an external system (DOM, network subscriptions, timers).

Mental Model

"The Satellite Dish: Whenever the satellite coordinates change (dependencies), you re-align the antenna and close the old signal."

Interactive Engine Simulation

Fiber Hooks Linked List
useState
"Initial"
useEffect
"Idle"

Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.

Executable Code Snippet

Component.jsx
JSX / React 19
1useEffect(() => {
2  // 1. Setup Logic
3  const sub = API.subscribe(id);
4
5  // 2. Cleanup Logic
6  return () => sub.unsubscribe();
7
8  // 3. Dependencies
9}, [id]);
Technical Takeaways & Best Practices
  • 01.Component re-renders are triggered by state or prop changes.
  • 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
  • 03.Automatic batching optimizes multiple state updates into a single render cycle.

01. Not a Lifecycle Hook

Forget `componentDidMount`. `useEffect` is about **Synchronization**. It synchronizes the component's state with an external system (an API, a WebSocket, or the window scroll position). It runs **after** the browser has finished painting to ensure the UI remains responsive.

Execution Cycle

Render Blueprints
Browser Paint
Run Setup Logic

02. The Cleanup Rule

Memory leaks happen when you forget to clean up. Every time an effect re-runs, React first calls the **Cleanup function** from the *previous* render cycle before running the new setup logic. This prevents accumulating multiple intervals or listeners.

Architectural Advice

"If you find yourself using 'useEffect' to update state based on other state, stop. That logic usually belongs in the event handler or directly in the render body. Effects should only be for 'external' systems."