Careeroza
useEffect Basics
Syntax
useEffect(() => {
// side effect: runs after React updates the screen
return () => {
// optional cleanup: runs before the next effect and on unmount
};
}, [dependencies]);| Dependency array | Effect runs |
|---|---|
| none | after every render |
| [] | once, after the first render (mount) |
| [a, b] | after the first render and whenever a or b change |
Update the Document Title
Example
The effect runs after every change of count (watch the console).
import { useState, useEffect } from 'react';
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Effect: count is now ' + count);
document.title = 'Clicked ' + count + ' times';
}, [count]);
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}Result