Before we understand useEffect , let’s understand what are Side effects.

Side effects

Side effects are operations that interact with the outside world or have effects beyond the component's rendering. Examples include:

These are called side effects because they don't just compute output based on the input—they affect things outside the component itself.


Problem in running side effects in React components

If you try to introduce side effects directly in the rendering logic of a component (in the return statement or before it), React would run that code every time the component renders. This can lead to:


How useEffect Manages Side Effects:

The useEffect hook lets you perform side effects in functional components in a safe, predictable way:

useEffect(() => {
  // Code here is the "effect" — this is where side effects happen
  fetchData();

  // Optionally, return a cleanup function that runs when the component unmounts.
  return () => {
    // Cleanup code, e.g., unsubscribing from an event or clearing timers.
  };
}, [/* dependencies */]);