useEffect — Your Bridge to the " Outside World "
Many beginners try to use useEffect as a replacement for " Lifecycle " methods (like in old React). But this is a dead end.
Correct mental model: useEffect is a synchronization tool. Your component lives inside React, while things like APIs, video players, chats, or timers live outside. The effect helps them agree.
1. First Picture, Then Code (Execution Order)
In React, the interface is always a priority.
- First, React calculates what to show.
- Then it draws it on screen (Paint).
- And only when the user already sees the result,
useEffectruns. Why like this? So heavy code (server request or animation setup) doesn't make the user stare at a white screen.
2. Remote Control (Dependency Array)
An effect is not an " event " . It's a description of how the component should synchronize.
[](Empty array): Synchronize once. " Hello, world! I appeared, let's load data " .[roomID]: " I'm watching the room. If the user moved to another room — reconnect me! " .- Without array: Chaos. The effect will run after every comma changed in code. Almost always this is an error leading to browser hang.
3. Cleanup Function: " Turn Off the Lights When Leaving "
Imagine you turned on music in a room. If you leave to another room without turning it off, the music will keep blaring. In programming, this is called memory leak.
The function you return from useEffect is your " cleaning service " .
useEffect(() => {
const timer = setInterval(() => console.log('Tick'), 1000);
// Cleanup:
return () => {
clearInterval(timer); // Turn off timer when it's no longer needed
};
}, []);
Important secret: Cleanup runs BEFORE each new effect execution and when the component is removed. React first " sweeps old garbage " , then brings " new order " .
4. Race Conditions: Who Came First?
If you're loading a user profile and the internet lags — data might arrive in the wrong order.
- You requested Ivan.
- Then requested Peter.
- Peter's data arrived quickly.
- Ivan's data (requested earlier) arrived later and overwrote Peter. Result: The page says " Peter " , but shows Ivan's photo.
Solution — the ignore flag:
useEffect(() => {
let ignore = false;
fetchData().then(res => {
if (!ignore) setVal(res);
});
return () => { ignore = true; };
}, [id]);
This hook is the most powerful and dangerous. Use it only when you really need to step outside React's pure world.