Lazy Initial State

Expensive Initial Value

// runs on EVERY render (result ignored after the first one)
const [items, setItems] = useState(JSON.parse(localStorage.getItem('items')));

// runs only once
const [items, setItems] = useState(() => JSON.parse(localStorage.getItem('items')) ?? []);

Exercise: Make a "Like" button that shows ♡ and toggles to ❤ with a like count.

Show answer
function Like() {
  const [liked, setLiked] = useState(false);
  return <button onClick={() => setLiked(l => !l)}>{liked ? '❤ 1' : '♡ 0'}</button>;
}