Toast NotificationLoading saved progress…

Toast

A toast is a small message that pops in to confirm something happened — "Saved successfully" — and then quietly disappears on its own a few seconds later. Building one in React is a lesson in one thing: a timer is a side effect, and side effects need to be tracked so you can cancel them.

What you'll build

The starter App.tsx renders a single Show notification button. Make it work:

  1. Show on click. Clicking the button reveals a toast reading Saved successfully.
  2. Auto-dismiss after 3s. A setTimeout hides the toast 3000ms later.
  3. Manual close. The toast has a × button that hides it immediately and cancels the pending timer.
  4. No stacked timers. Clicking Show again while a toast is up resets the countdown instead of piling up timeouts.

Examples

  • Click Show: the toast slides in. Do nothing for 3 seconds — it vanishes on its own.
  • Click Show, then hit × right away: the toast disappears now, and the 3s timer never fires (because you cleared it).
  • Click Show three times fast: you see one toast, and it dismisses 3 seconds after the last click — not three separate timeouts firing.

Notes

  • Keep a single toast. One visible boolean plus a fixed message — not a queue. That's the EASY version.
  • The timeout id is not UI state. Store it in a useRef, not useState — nothing renders from it, and changing it should not trigger a re-render.
  • Always clear before you set. Cancel any existing timer at the top of show so rapid clicks can't stack timeouts.
  • Clean up on unmount. A useEffect cleanup that clears the timer stops it firing after the component is gone.
Loading editor…
Loading preview…