Effective useState & useEffect: Avoiding infinite loops
On this page
State & Effects Mastery
Hooks are the power of React, but they are also the most common source of bugs. useState manages data, and useEffect manages Side Effects (API calls, subscriptions). If you don't understand the "Dependency Array," you will crash your browser.
1. The Dependency Array Rule
The second argument to useEffect tells React when to run the effect.
- No Array: Runs on EVERY render. (Extremely dangerous).
- Empty Array []: Runs only once on Mount. (Perfect for initial API calls).
- [data]: Runs only when 'data' changes.
2. The Infinite Loop Trap
If you call setData() inside a useEffect that has 'data' in its dependency array, you create a loop: Effect -> State Change -> Re-render -> Effect -> State Change... until the tab crashes.
3. Cleanup Functions
Always return a cleanup function to prevent Memory Leaks. If you set a setInterval or a WebSocket, you must clear it when the component unmounts.
4. Interview Mastery
Q: "What is the difference between useEffect and useLayoutEffect?"
Architect Answer: "`useEffect` runs *asynchronously* after the render is painted on the screen. It is non-blocking. `useLayoutEffect` runs *synchronously* after all DOM mutations but *before* the browser paints. You should use `useLayoutEffect` only when you need to measure DOM elements (like a tooltip position) and update them before the user sees a 'flicker'."