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
buttonAdd to cartadds one to a count shown in apwith the idcountasN items in your cart(1 item in your cartfor one). - An effect sets
document.titletoCart (N)whenever the count changes, starting withCart (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>
);
}