Sync the browser tab title with a counter. See exactly when React runs an effect: after the page has been updated.
React · beginner · 7 min · 18 steps · free
import { useState, useEffect } from 'react';
export default function ClickTitle() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
console.log('effect ran, count =', count);
});
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}<ClickTitle> for the first time: it calls the ClickTitle function.useState runs for the first time, so React stores the starting value for count and returns it: 0.useEffect hands React a function to run later, after the page is updated. Nothing inside it runs yet.ClickTitle returns JSX: a description of what the screen should show, <button>Clicked 0 times</button>. React has not changed the page yet.onClick handler.setCount(count + 1) does not change count right away: React queues the update and will render again. In this call count is still 0.<ClickTitle> again (render 2): it calls ClickTitle once more, from the top.useState returns the value React has kept for count: 1. The starting value is only used on the first render.useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.ClickTitle returns JSX: a description of what the screen should show, <button>Clicked 1 times</button>. React has not changed the page yet.Answer: After React updates the page
Answer: No, it is a side effect: use an effect
← Forms and Controlled Inputs · Effect Dependencies →