React useEffect Deep Dive
A React component should theoretically only calculate the output UI given some inputs (props and state). Any operation that affects something outside the component is a Side Effect.
The Problem
If you put a fetch() request or a setTimeout() directly in the body of a component, it will re-execute every single time the component re-renders. This leads to infinite loops and terrible performance.
The Solution: Dependency Array
The useEffect hook provides a way out. By passing a dependency array as the second argument:
- No array: Runs after every single render. (Rarely used)
- Empty array []: Runs only once after the initial render (mount). Great for initial data fetching.
- Array with vars [x, y]: Runs initially, AND whenever `x` or `y` changes between renders.
Cleanup Phase
If your effect sets up a subscription or interval, you MUST clean it up. You do this by returning a function from your effect. React will run this cleanup function when the component unmounts, or before running the effect again.
View Full Transcript+
This section contains the detailed mechanics of useEffect for accessibility. We covered how rendering works before effects run, how the dependency array triggers comparisons (using Object.is), and why the cleanup function is critical for preventing memory leaks in modern React architectures.
