A side effect is an observable interaction caused by evaluating a component beyond returning its rendered result. In React, useEffect places this work alongside the component lifecycle instead of performing it directly during rendering. section 6.1.4 section 4.2.1
Use an effect when component work must synchronize with something outside its immediate render:
- Run once on mount by passing an empty dependency array, such as loading remote options for a drop-down. section 6.1.1
- Run when selected values change by listing them in the dependency array, such as updating document.title when a blog title changes. section 6.1.4
- Return a cleanup function when external work may outlive the component, such as a request continuing after unmount. section 6.1.1
Synchronizing the document title
function BlogPost({ title, body }) { useEffect(() => { document.title = title; }, [title]); return <article><h1>{title}</h1>{body}</article>; } The effect runs on mount and whenever title changes, but not merely because another property changes. section 6.1.4
Listing 6.3 Side effect executed in hook
import { useEffect } from "react";
function BlogPost({ title, body }) {
useEffect(() => {
document.title = title; #1
}, [title]); #2
return (
<article>
<h1>{title}</h1>
{body}
</article>
);
}
function App() {
return (
<main>
<BlogPost title="First post" body={
<p>Welcome to my cool website.</p>
} />
</main>
);
}
export default App;
Inspect the complete BlogPost component and its dependency array. section 6.1.4























