Unmounting means a component is being removed from the screen
Side effects
Side effects are operations that interact with the outside world or have effects beyond the component's rendering. Examples include:
- Fetching data from an API.
- Modifying the DOM manually.
- Subscribing to events (like WebSocket connections, timers, or browser events).
- Starting a clock
useEffect
lets your component do something after it shows up on the screen.
This “something” is often:
- Fetching data from a server
- Setting up event listeners (like scroll or resize)
- Updating the page title
- Animating elements
- Cleaning things up when the component disappears
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:
- Unnecessary or duplicated effects (like multiple API calls).
- Inconsistent behavior (side effects might happen before rendering finishes).