useEffect: Code That Runs After Render

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

What you'll learn

UseEffect.jsx

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>;
}

Step by step

  1. React renders <ClickTitle> for the first time: it calls the ClickTitle function.
  2. useState runs for the first time, so React stores the starting value for count and returns it: 0.
  3. useEffect hands React a function to run later, after the page is updated. Nothing inside it runs yet.
  4. ClickTitle returns JSX: a description of what the screen should show, <button>Clicked 0 times</button>. React has not changed the page yet.
  5. React turns the JSX into real page elements and shows them: look at the Screen panel.
  6. The button is on the page, so React now runs the effect.
  7. It sets the browser tab's title to "Clicked 0 times". This is a side effect: it changes something outside React.
  8. Prints “effect ran, count = 0”.
  9. You click the “Clicked 0 times” button. React calls its onClick handler.
  10. setCount(count + 1) does not change count right away: React queues the update and will render again. In this call count is still 0.
  11. React renders <ClickTitle> again (render 2): it calls ClickTitle once more, from the top.
  12. useState returns the value React has kept for count: 1. The starting value is only used on the first render.
  13. useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.
  14. ClickTitle returns JSX: a description of what the screen should show, <button>Clicked 1 times</button>. React has not changed the page yet.
  15. React compares the new JSX with the last one and updates only what changed on the page.
  16. After the new render reaches the page, React runs the effect again.
  17. The tab title is now "Clicked 1 times".
  18. Prints “effect ran, count = 1”.

Common mistakes

Best practices

Key takeaways

Check yourself

When does an effect run?

Answer: After React updates the page

Is setting document.title in the component body OK?

Answer: No, it is a side effect: use an effect

·

More in Effects and Refs