Great question! It is super simple to use. You will just need to provide the following:
callback
to be called once the timer completes,timeout
is the time in milliseconds for the timer,- and an optional
options
object. So far, the only option that you can provide is apauseOnReset
which is aboolean
value determining whether or not the countdown should pause after theresetCountdown
handler is invoked.
The hook then provides four useful properties:
isActive
is aboolean
value that determines if the countdown is currently active.countdown
is the time left in milliseconds. This might be useful if you want to present the user how much time is left in the countdown.toggleCountdown
is a function that starts and stops the countdown.resetCountdown
will stop the countdown and reset the countdown to the initialtimeout
.
Heres an example usage:
function App() {
const [time, setTime] = React.useState(10000);
const [complete, setComplete] = React.useState(false);
const [pauseOnReset, setPauseOnReset] = React.useState(false);
const { toggleCountdown, isActive, countdown, resetCountdown } = useCountdown(
() => setComplete(true),
time,
{ pauseOnReset }
);
if (complete) {
return <h1>{"⏰ TIMES UP!"}</h1>;
}
return (
<div className="App">
<h1>{`${countdown / 1000} seconds`}</h1>
<p>{isActive ? "COUNTING DOWN" : "PAUSED"}</p>
<label htmlFor="timeout-slider">Time: </label>
<input
id="timeout-slider"
step="1000"
min="1000"
max="20000"
type="range"
value={time}
onChange={event => setTime(event.target.value)}
/>
<button onClick={toggleCountdown}>{isActive ? "PAUSE" : "START"}</button>
<button onClick={resetCountdown}>RESET</button>
<button onClick={() => setPauseOnReset(prev => !prev)}>
{pauseOnReset ? "👍" : "👎"}
</button>
</div>
);
}