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 Walkthrough
Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.
Reference Code Snippet
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]);- 01.Effects run after the browser paints the screen to avoid blocking visual rendering.
- 02.The cleanup function returned by useEffect runs before the next effect run and on component unmount.
- 03.Always list all reactive values (props, state) used inside the effect in the dependency array.
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
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."