useEffect

useEffect is the React Hook for running side effects in a component, such as fetching data, setting up subscriptions, or updating the document title. It runs after the component renders.

React

A side effect is anything that reaches outside React's normal render — talking to a server, using a timer, or interacting with the browser directly. You put that code inside useEffect so it runs at the right time.

The second argument is a dependency array that controls when the effect re-runs: an empty array [] runs it once after the first render, while listing variables re-runs it whenever those change. If your effect sets up something ongoing (like a timer), you return a cleanup function to tear it down.

Syntax

useEffect(() => { /* effect */ return () => { /* cleanup */ } }, [deps]);

Examples

JSX — Updates the browser tab title to match the count every time the count state changes.

import { useState, useEffect } from "react";

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

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

Learn it in a lesson

See also

Back to the Dictionary