Thuta Learning
IntermediateWeb Developmentintermediate

useEffect Hook

Relax. We'll talk through this in plain words — no textbook voice.

`useEffect` is the hook you reach for when you need to run a side effect after a component renders. A side effect is anything outside React's normal render calculation — calling an API, changing the browser title, setting up a timer, attaching an event listener.

jsx
import { useEffect, useState } from 'react';

function TitleChanger() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = 'You clicked ' + count + ' times';
  }, [count]);

  return (
    <button onClick={() => setCount(count + 1)}>
      Click to change title ({count})
    </button>
  );
}

Every time `count` changes, the code inside `useEffect` runs and updates the browser tab title. Since `[count]` is in the dependency array, it only runs when count actually changes.

You should see
Every button click bumps the on-screen count, and the browser tab title updates too, changing to something like `You clicked 1 times`.

Info

If you update state inside an effect and get the dependencies wrong, you can end up with an infinite loop. Be clear about exactly why you want the effect to run.

Easy traps

  • If you don't think carefully about the dependency array, you can end up with unnecessary rerenders or effects firing more than they should.
useEffect Hook | Thuta Learning