封装倒计时自定义react hook

ts 复制代码
import { useEffect, useState, useRef } from 'react'

const useCountDown = (initialTime = 60) => {
  let timerRef = useRef<any>(null)
  const [countdown, setCountdown] = useState(initialTime);
  const [isCounting, setIsCounting] = useState(false);

  const startCountDown = () => {
    if (!isCounting) {
      setCountdown(initialTime)
      setIsCounting(true)
      timerRef.current = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timerRef.current)
            setIsCounting(false)
            return initialTime
          }
          return prev - 1
        }
        )
      }, 1000)
    }
  }

  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  return {
    countdown,
    isCounting,
    startCountDown
  }
}

export default useCountDown

使用

ts 复制代码
  const {
    countdown,
    isCounting,
    startCountDown
  } = useCountDown()
  
 const handleGetCode = () => {
    if(isCounting)return
    startCountDown()
  }
  
  ...
  
<AtButton type='primary' onClick={handleGetCode}>{isCounting ? `${countdown}秒后重试` : '获取验证码'}</AtButton>
相关推荐
问商十三载8 分钟前
RAG的适用边界在哪里?2026年价值与局限详解
大数据·前端·人工智能
爱勇宝1 小时前
人生没有最好的年龄,只有最好的状态
前端
mONESY1 小时前
React + TypeScript 入门到进阶:从 Props 类型约束到状态管理与副作用最佳实践
javascript
幼儿园技术家1 小时前
前端 Node 全家桶
前端·js or ts
无人生还1 小时前
从 Vue3 到 React · 快速上手系列第 9 篇:自定义 Hook(对标 Composables)
前端·vue.js·react.js
张龙6871 小时前
RAG 知识库问答系统实战:分块、混合检索、RRF 融合与重排全链路拆解
前端
用户1306095607231 小时前
第二章学完后,我对 webpack5 前端工程化的一点理解
前端
a1117761 小时前
小鸡下蛋 小游戏 html
前端·开源·html
码哥DFS1 小时前
算法练习day1-备战2027届秋招
前端·javascript·数据结构·算法
DevOpenClub1 小时前
用网页快照、静态 HTML 和 PDF 转换接口构建网页归档 Agent
前端·人工智能·pdf·html