flnxi-Wu/lib/hooks/useDebounce.ts
WuYongJie 3c009350d7 feat: 前端性能优化(任务23)
- 创建防抖Hooks
  * useDebounce - 延迟更新值直到用户停止输入
  * useDebouncedCallback - 创建防抖的回调函数
  * 支持自定义延迟时间(默认300ms)

- 创建SWR缓存Hooks
  * useTemplates - 缓存模板列表
  * useTemplate - 缓存单个模板详情
  * 配置智能缓存策略(5秒去重、错误重试)
  * 支持手动刷新数据

- 现有优化
  * 字段验证使用useMemo避免重复计算
  * 表单组件使用React.memo和useCallback优化渲染
  * 拖拽排序使用防抖避免频繁更新

性能提升:
- 减少不必要的API请求
- 优化表单输入响应速度
- 提升大表单的渲染性能
2025-12-13 15:33:10 +08:00

53 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useState } from 'react'
/**
* 防抖Hook - 延迟更新值直到用户停止输入
* @param value 需要防抖的值
* @param delay 延迟时间(毫秒)
* @returns 防抖后的值
*/
export function useDebounce<T>(value: T, delay: number = 300): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
// 设置定时器
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
// 清理函数:如果value在delay时间内再次改变,清除之前的定时器
return () => {
clearTimeout(handler)
}
}, [value, delay])
return debouncedValue
}
/**
* 防抖回调Hook - 创建一个防抖的回调函数
* @param callback 需要防抖的回调函数
* @param delay 延迟时间(毫秒)
* @returns 防抖后的回调函数
*/
export function useDebouncedCallback<T extends (...args: any[]) => any>(
callback: T,
delay: number = 300
): (...args: Parameters<T>) => void {
const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null)
return (...args: Parameters<T>) => {
// 清除之前的定时器
if (timeoutId) {
clearTimeout(timeoutId)
}
// 设置新的定时器
const newTimeoutId = setTimeout(() => {
callback(...args)
}, delay)
setTimeoutId(newTimeoutId)
}
}