Before we understand useEffect
, let’s understand what are 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.
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:
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 */]);
useEffect
is the effect function, where you put the code that performs the side effect.[]
, the effect will only run once after the initial render.