DEV Community

Aanand
Aanand

Posted on

useEffect hook Simple and accurate explanation

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");
});
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ No control β†’ runs again and again
πŸ‘‰ Usually a bad idea

2.Run only once (on mount)

useEffect(() => {
  console.log("Runs only once");
}, []);
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Like: β€œDo this when the page loads”

3.Run when something changes (MOST IMPORTANT)

useEffect(() => {
  console.log("Runs when count changes");
}, [count]);

Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ β€œOnly run when count changes”

Top comments (0)