24. useEffect (Side Effects)
Handling the Outside World
A React component's primary job is pure: it takes data (props/state) and returns UI (JSX). Anything that happens outside of this pure rendering process—like fetching data from a server, setting a timer, or manually interacting with the browser's DOM—is called a Side Effect. We manage these safely using the useEffect hook.
The Anatomy of useEffect
The useEffect hook takes two arguments: a callback function to run, and an optional dependency array that controls exactly when the function runs.
The Dependency Array Rules
The dependency array dictates the execution timing of your effect. Getting this wrong is the #1 cause of bugs in React.
- No array:
useEffect(() => {...})Runs after EVERY single render. This is extremely dangerous and easily causes infinite loops if you update state inside. - Empty array:
useEffect(() => {...}, [])Runs EXACTLY ONCE when the component first mounts (appears on the screen), and never again. - With variables:
useEffect(() => {...}, [userId])Runs on mount, AND subsequently whenever the value of `userId` changes.
The Cleanup Function
If your effect creates an ongoing process (like a setInterval or an Event Listener on the window), you must clean it up when the component leaves the screen to prevent memory leaks.
Knowledge Check
Ready to test your understanding of 24. useEffect (Side Effects)?