A component can render a timer’s numbers with JSX, but the timer also needs an interval that starts and stops. `useEffect` runs that work outside rendering. It takes a function for the effect, an optional dependency array that controls when it runs, and an optional cleanup function returned by the effect. section 6.0 section 6.1
Update the browser title
```jsx import { useEffect } from "react"; function BlogPost({ title, body }) { useEffect(() => { document.title = title; }, [title]); return <article><h1>{title}</h1>{body}</article>; } ``` The effect runs on mount and when `title` changes. A re-render caused only by another value does not require another title update. section 6.1.4
Choose dependencies to match the work:
- `[]` runs the effect on mount, rather than again for ordinary re-renders. Use it when loading data once or starting an interval for the component’s lifetime. section 6.1 section 6.5
- `[value]` runs it on mount and when that dependency changes. If a previous run returned cleanup, cleanup runs before the next effect; it also runs on unmount. section 6.1 section 6.1.4
- Omitting the array is different from supplying `[]`: use an empty array when updates should not repeat the effect. section 6.1.3 section 6.5
Figure 6.1 The useEffect hook here is displayed both as a code snippet and a flowchart. The hook contains an optional effect as well as an optional cleanup function. The effect runs on mount, and the cleanup runs on unmount—if they’re defined, of course. Furthermore, if the effect has a dependency array, the cleanup and effect will also run every time any value reference in the dependency array changes.
The flowchart shows where the effect and its optional cleanup fit around mounting, dependency changes, and unmounting. section 6.1
Clean up a browser listener
```jsx useEffect(() => { const onResize = () => setSize(getWindowSize()); window.addEventListener("resize", onResize); return () => window.removeEventListener("resize", onResize); }, [setSize]); ``` The browser’s `resize` event is not managed by React. Attaching the listener in an effect and removing that same listener in cleanup keeps it from lingering after the component unmounts. section 8.8.1
The same setup-and-cleanup pattern starts and clears a countdown interval as its running state changes. Keep hooks at the top level of functional components, not inside conditions or loops. Class components use life cycle methods for similar jobs; `useEffect` is not always a synchronous substitute for them. section 6.1.5 section 7.8 section 6.3.3



