UNPKG

@boomerang-io/utils

Version:

A library of reusable utilities and hooks for React webapps on the Boomerang platform.

27 lines 686 B
import { useState, useEffect, useRef } from "react"; function useCountdown(_ref) { let { countdown, onCountdownEnd, reset } = _ref; const [ct, setCountdown] = useState(countdown); const timer = useRef(null); useEffect(() => { if (reset) setCountdown(countdown); if (ct < 1) { setCountdown(countdown); onCountdownEnd(); } clearInterval(timer.current); const countdownCounter = () => { setCountdown(ct - 1); }; timer.current = setInterval(countdownCounter, 1000); return function cleanup() { clearInterval(timer); }; }, [reset, ct, countdown, onCountdownEnd]); return ct; } export default useCountdown;