React: Keep the title in step

Use an effect to keep something outside React, the page title, matching the state.

What to build

A button that adds to a cart, and a page title that always shows the cart's size.

Requirements

  • A button Add to cart adds one to a count shown in a p with the id count as N items in your cart (1 item in your cart for one).
  • An effect sets document.title to Cart (N) whenever the count changes, starting with Cart (0).

Constraints

Set the title in an effect, not in the click handler.

Example

After two clicks the page says "2 items in your cart" and the title is "Cart (2)".

Why it works

The effect runs after each render where the count changed, so the title follows the state no matter what changed it.

Hints

Hint 1

useEffect(() => { document.title = ...; }, [count]);

Hint 2

Choose "item" or "items" from the count.

Solution

Show one correct solution (try it yourself first)
import { useEffect, useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = "Cart (" + count + ")";
  }, [count]);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Add to cart</button>
      <p id="count">
        {count} {count === 1 ? "item" : "items"} in your cart
      </p>
    </div>
  );
}

Lesson: Effects: syncing with the outside world →