React has one job:
π Take data β show UI
But real apps need more than just showing UI. You also need to:
- fetch data from APIs
- set timers
- store data
- listen to events
These things are outside Reactβs job.
So useEffect lets you run code after React updates the screen, especially for things outside React.
π React renders UI
π Then useEffect runs side work
β οΈ The part most people miss (important)
useEffect is not just βrun after renderβ
Itβs: βRun after render β but only when something changes (if you tell it what to watch)β
The 3 real behaviors (this is where clarity comes)
1.Run every time (default)
useEffect(() => {
console.log("Runs after every render");
});
π No control β runs again and again
π Usually a bad idea
2.Run only once (on mount)
useEffect(() => {
console.log("Runs only once");
}, []);
π Like: βDo this when the page loadsβ
3.Run when something changes (MOST IMPORTANT)
useEffect(() => {
console.log("Runs when count changes");
}, [count]);
π βOnly run when count changesβ
Top comments (0)