A component that changes the browser title, fetches data, starts a timer, or subscribes to a service reaches beyond React’s normal state-to-UI flow. That outside interaction is a side effect. section 4.1.1 section 4.4
React components generally transform state into UI; side effects deliberately perform additional work such as network requests, subscriptions, DOM manipulation, logging, storage access, or element measurement. Function components use hooks to keep that work with related state, UI, and cleanup code. section 1.1.3 section 1.3.1
Manage side effects with useEffect according to when the work should run:
- Pass only an effect function to run it after every render. section 4.1.1 section 4.4
- Pass an empty dependency array to run the effect once when the component mounts. section 4.4
- List effect dependencies to rerun the effect when their values change. section 4.4
- Return a cleanup function to cancel unfinished work or unsubscribe before rerunning and when the component unmounts. section 1.3.1 section 4.4
- Keep separate side effects in separate useEffect calls, and place asynchronous functions inside the effect. section 4.4
Updating the browser title
A SayHello component stores a greeting index in state. Clicking Say Hi changes the index, React rerenders, and useEffect updates document.title after the browser repaints. The effect reads greetings and index from the component scope. section 4.1.1
Listing 4.1 Updating the browser title
import React, { useState, useEffect } from "react"; #1
export default function SayHello () {
const greetings = ["Hello", "Ciao", "Hola", "こんにちは"];
const [index, setIndex] = useState(0);
useEffect(() => { #2
document.title = greetings[index]; #3
});
function updateGreeting () {
setIndex(Math.floor(Math.random() * greetings.length));
}
return <button onClick={updateGreeting}>Say Hi</button>
}
#1 Import the useEffect hook.
#2 Pass the useEffect hook a function, the effect.
#3 Update the browser title from inside the effect.
Inspect the focused JSX example showing state, an effect, a user event, and an imperative browser update working together. section 4.1.1























