Chapter 1 of 4

What an Effect Is

Synchronising with systems outside React, and when the effect body runs.

Rendering must be pure: given the same props and state, a component returns the same output and changes nothing outside itself. But real applications do need to touch the outside world - subscribe to a socket, set the document title, start an animation.

useEffect is where that work goes. It runs after React has committed the render to the DOM, so the screen is already up to date when your code runs.

import { useEffect, useState } from "react";

function PageTitle({ unreadCount }) {
  useEffect(() => {
    document.title = unreadCount > 0 ? `(${unreadCount}) Inbox` : "Inbox";
  });

  return <h1>Inbox</h1>;
}

The order of events

  1. State or props change.
  2. React calls the component and gets a new element tree.
  3. React commits the differences to the DOM.
  4. The browser paints.
  5. React runs your effects.

What counts as an effect

  • Subscribing to something: a WebSocket, an event listener, an observer.
  • Fetching data when a component appears or its inputs change.
  • Controlling a non-React widget such as a map or a chart library.
  • Timers and intervals.