useCountdown
Create countdown timers using useCountdown.
Install:
Note: This hook depends on React’s experimental useEffectEvent.
npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental
Description:
The useCountdown hook is useful for creating a countdown timer. By specifying an endTime and various options such as the interval between ticks and callback functions for each tick and completion, the hook sets up an interval that updates the count and triggers the appropriate callbacks until the countdown reaches zero. The countdown value is returned, allowing you to easily incorporate and display the countdown in your components.
Parameters
Name | Type | Description |
---|---|---|
endTime | number | The end time of the countdown in milliseconds since the Unix epoch. |
options | object | An object containing the following options:
|
Return Value
Name | Type | Description |
---|---|---|
count | number | The current count of the countdown. |
Demo:
Example:
import * as React from "react";
import { useCountdown } from "@uidotdev/usehooks";
export default function App() {
const [endTime, setEndTime] = React.useState(new Date(Date.now() + 10000));
const [complete, setComplete] = React.useState(false);
const count = useCountdown(endTime, {
interval: 1000,
onTick: () => console.log("tick"),
onComplete: (time) => setComplete(true),
});
const handleClick = (time) => {
if (complete === true) return;
const nextTime = endTime.getTime() + time;
setEndTime(new Date(nextTime));
};
return (
<section>
<header>
<h1>useCountdown</h1>
</header>
<span className="countdown">{count}</span>
{complete === false && (
<div className="button-row">
<button onClick={() => handleClick(5000)}>+5s</button>
<button onClick={() => handleClick(10000)}>+10s</button>
<button onClick={() => handleClick(15000)}>+15s</button>
</div>
)}
</section>
);
}