Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 07 / Topic 3 of 6

Custom hooks share logic, not state

examples/03_use_toggle.jsx packages up "a boolean, plus a function that flips it" into useToggle - the exact wishlist-heart pattern this course has already written by hand twice (Part 3, Part 6):

// examples/03_use_toggle.jsx
export function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  function toggle() {
    setValue((current) => !current);
  }

  return [value, toggle];
}

export function WishlistHeart({ label }) {
  const [isWishlisted, toggle] = useToggle(false);
  return (
    <button onClick={toggle}>
      {label}: {isWishlisted ? "♥ Wishlisted" : "♡ Add to wishlist"}
    </button>
  );
}

Rendering two WishlistHearts and clicking only the first one's button really only flips that one - the second stays exactly as it started (examples/03_use_toggle.test.jsx). Both instances call the identical useToggle function, but each call creates its own useState slot, the same way two separate calls to useState(0) never share a count. This is the single most important thing to internalize about custom hooks: they are reused code, not shared data. Section 6's exercise - and Part 9's useContext - exist specifically for the moment a value needs to be the same value across components, which a custom hook alone never gives you.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide