useCountdown

MediumWalmart

Prompt

Build a React hook called useCountdown that runs a countdown from a starting number of seconds down to zero.

const { isRunning, start, stop, seconds } =
useCountdown(totalTime);

What the hook returns:

  • seconds: the current number of seconds left. Starts at totalTime.
  • isRunning: true while the countdown is active, false otherwise.
  • start: a function that begins the countdown.
  • stop: a function that ends the countdown and puts seconds back to totalTime.

How the countdown behaves:

  • At the start, the countdown is idle: seconds is totalTime and isRunning is false.
  • After calling start(), seconds drops by 1 every second until it reaches zero.
  • If stop() is called at any point, the countdown ends right away and seconds returns to totalTime.
  • When the countdown runs all the way to zero on its own, the hook behaves as if stop() was called: isRunning becomes false and seconds is reset to totalTime.

What the demo page should show:

  • Two buttons: one labeled Start, one labeled Stop.
  • While the countdown is running, display the current value of seconds.
  • While the countdown is idle, display the text No Timer Running.