import { useState, useEffect, useRef, useCallback } from "react" /** * 倒计时 Hook * 用于验证码发送等场景的倒计时控制 */ export const useCountdown = (initialSeconds = 60) => { const [countdown, setCountdown] = useState(0) const timerRef = useRef | null>(null) useEffect(() => { if (countdown > 0) { timerRef.current = setInterval(() => { setCountdown((prev) => prev - 1) }, 1000) } else if (timerRef.current) { clearInterval(timerRef.current) timerRef.current = null } return () => { if (timerRef.current) clearInterval(timerRef.current) } }, [countdown]) const start = useCallback(() => { setCountdown(initialSeconds) }, [initialSeconds]) const reset = useCallback(() => { setCountdown(0) }, []) return { countdown, isRunning: countdown > 0, start, reset, } }