useEffect is a React Hook that lets you synchronize a component with external systems, such as APIs, timers, event listeners, or third-party libraries.
useEffect?An effect runs after React commits a render. Its dependency array determines when React re-runs the effect.
useEffect(() => {// Side effect}, [dependencies]);
Example: Timer
useEffect(() => {const id = setInterval(() => {console.log("tick");}, 1000);return () => clearInterval(id);}, []);
The timer starts when the component mounts and stops when the component unmounts.
Some effects create ongoing work, such as timers, event listeners, or subscriptions. Return a cleanup function to stop that work when the effect is re-run or the component unmounts.
useEffect(() => {const handleResize = () => {console.log(window.innerWidth);};window.addEventListener("resize", handleResize);return () => {window.removeEventListener("resize", handleResize);};}, []);
The cleanup function removes the event listener, preventing duplicate subscriptions and unwanted behavior.
The dependency array determines when an effect runs again.
// After every commituseEffect(() => {console.log("Rendered");});// When the component mounts, and during Strict Mode's// extra development setup cycleuseEffect(() => {console.log("Mounted");}, []);// When count changesuseEffect(() => {console.log(count);}, [count]);
React compares dependencies using Object.is. Include every reactive value used by the effect to avoid stale values.