useEffect
useEffectruns side effects after React renders, and you use it when your component needs to sync with something outside React like APIs, timers, or event listeners.
useEffect(() => {const id = setInterval(() => {console.log("tick");}, 1000);}, []);
Some effects start work that keeps running after render, like event listeners or timers. The cleanup function stops that work when it’s no longer needed.
useEffect(() => {const handleResize = () => {console.log(window.innerWidth);};window.addEventListener("resize", handleResize);return () => {window.removeEventListener("resize", handleResize);};}, []);
In this example, the effect adds a resize listener when the component mounts.
The cleanup function removes it when the component unmounts, preventing duplicate listeners, memory leaks, and unexpected behavior caused by stale effects still running.