Synchronize your components with the outside world using useEffect, mastering dependencies and cleanup.
Open this lesson in KodokonA React component computes JSX from props and state. Anything outside that scope - changing the document title, starting a timer, subscribing to a browser event - is a side effect. useEffect runs that code after rendering, without blocking the display, and re-synchronizes it when certain values change.
import { useEffect } from "react";
function CartTitle({ count }) {
useEffect(() => {
document.title = `Cart (${count})`;
}, [count]);
return <p>Items: {count}</p>;
}The dependency array controls how often the effect runs. [count]: the effect re-runs after every render where count changed. []: the effect runs only once, after the first render. No array: the effect re-runs after every render, which is rarely what you want. Golden rule: every component value used inside the effect must appear in the array.
import { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>Elapsed: {seconds} s</p>;
}The function returned by the effect is the cleanup function. React calls it before each new run of the effect, then one last time when the component unmounts. It is what prevents leaks: orphaned timers, stacked-up listeners, subscriptions that are never cancelled. Every effect that “opens” something must close it again.
useEffect(() => {
function onResize() {
setWidth(window.innerWidth);
}
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
};
}, []);useEffect(fn, []), when is the function fn executed?userId but its dependency array is []. What is the problem?