- Published on
useCountdown Hook React
![useCountdown Hook React](https://user-images.githubusercontent.com/33494971/269602373-9aa20fcb-72ca-49ca-902c-e5866a74bf0e.png)
useCountdown Hook React
useCountdown Code and Usage
useCountdown is a hook to implement a countdown timer.
import { useState, useEffect } from "react";
const useCountdown = (initialTime) => {
const [time, setTime] = useState(initialTime);
useEffect(() => {
if (time > 0) {
const timer = setInterval(() => {
setTime((prevTime) => prevTime - 1);
}, 1000);
return () => {
clearInterval(timer);
};
}
}, [time]);
return time;
};
// Usage
const CountdownExample = () => {
const countdownTime = useCountdown(10);
return (
<div>
<p>Countdown: {countdownTime}</p>
</div>
);
};