Run side effects in function components using the useEffect hook.
A side effect is anything that reaches outside of the render cycle: data fetching, subscriptions, timers, DOM manipulation. React's useEffect hook lets you run effects after the component renders.
import { useEffect } from "react";
useEffect(() => {
document.title = "Hello from React";
});
Without a second argument, this runs after every render — usually too much.
The second argument controls when the effect runs:
// Run once on mount
useEffect(() => {
fetchData();
}, []);
// Run when 'query' changes
useEffect(() => {
search(query);
}, [query]);
Return a function to clean up the effect (clear timers, cancel subscriptions, etc.):
useEffect(() => {
const id = setInterval(() => setTick(t => t + 1), 1000);
return () => clearInterval(id); // cleanup
}, []);
const [data, setData] = useState<string | null>(null);
useEffect(() => {
// Simulate fetching
setTimeout(() => setData("Loaded!"), 1000);
}, []);
Build a component that:
count state starting at 0useEffect to update the document title to "Count: {count}" every time count changes<p> elementThe tests will click Increment and check that document.title updates.
import { useState, useEffect } from "react"; export default function App() { const [count, setCount] = useState(0); // Use useEffect to sync document.title with count return ( <div> <p>{count}</p> <button onClick={() => setCount(c => c + 1)}>Increment</button> </div> ); }