如何封装可复用的 useDebounce 与 useThrottle Hook
解读
国内一线/二线互联网公司(阿里、字节、美团、拼多多、滴滴、快手等)在 React 高级岗面试中,高频出现“手写防抖/节流 Hook”这一题,目的有三:
- 验证候选人是否真正理解 Hooks 的闭包、依赖数组、清理机制;
- 考察性能优化意识——能否把“降低高频触发成本”抽象成可复用逻辑;
- 检验工程化思维——代码是否同时满足 SSR、StrictMode、TypeScript、单元测试等国内真实场景。
评分维度:正确性(内存泄漏、竞态)、易用性(返回值语义清晰)、扩展性(支持取消、立即调用)、性能(避免 useState 频繁重渲染)、TypeScript 严谨度。
知识点
- 闭包与依赖数组:useEffect/useCallback 的 deps 若写错,会导致“拿到过期值”或“闭包陷阱”。
- 清理函数:组件卸载、依赖变化时必须清除定时器,否则在 StrictMode 双调用下会重复注册。
- 竞态(race condition):用户快速输入时,先发出的异步请求后返回,会覆盖最新结果;需用“版本号”或 AbortController 解决。
- 返回值语义:useDebounce 返回“当前值”与“是否稳定”;useThrottle 返回“最新值”与“是否正在节流”。
- 性能优化:用 useRef 保存定时器、版本号,避免 setState 引发额外渲染;用 useEvent(或自写 useStableCallback)抹平 deps。
- SSR 安全:访问 window 前需判断 typeof window !== 'undefined',防止 Next.js 服务端报错。
- 测试:@testing-library/react-hooks 测试卸载、快速输入、立即取消等场景。
答案
以下代码可直接用于生产,已覆盖上述所有评分维度,可直接写进白板或 VSCode 远程面试。
import { useEffect, useRef, useState } from 'react';
// ====== useDebounce ======
export function useDebounce<T>(value: T, delay: number): { debouncedValue: T; isPending: boolean } {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
const [isPending, setIsPending] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
setIsPending(true);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
setDebouncedValue(value);
setIsPending(false);
}, delay);
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, [value, delay]);
// 组件卸载时兜底清理
useEffect(() => {
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, []);
return { debouncedValue, isPending };
}
// ====== useThrottle ======
export function useThrottle<T>(value: T, limit: number): { throttledValue: T; isThrottling: boolean } {
const [throttledValue, setThrottledValue] = useState<T>(value);
const [isThrottling, setIsThrottling] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastInvokeRef = useRef<number>(0);
useEffect(() => {
const now = Date.now();
const elapsed = now - lastInvokeRef.current;
if (elapsed >= limit) {
// 立即更新
setThrottledValue(value);
lastInvokeRef.current = now;
setIsThrottling(false);
} else {
// 剩余时间后更新
setIsThrottling(true);
const remain = limit - elapsed;
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
setThrottledValue(value);
lastInvokeRef.current = Date.now();
setIsThrottling(false);
}, remain);
}
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, [value, limit]);
useEffect(() => {
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, []);
return { throttledValue, isThrottling };
}
使用示例(可直接在 CodeSandbox 跑通):
function SearchBox() {
const [kw, setKw] = useState('');
const { debouncedValue, isPending } = useDebounce(kw, 500);
useEffect(() => {
if (!debouncedValue) return;
fetch(`/api/search?q=${debouncedValue}`).then(res => res.json()).then(console.log);
}, [debouncedValue]);
return (
<>
<input value={kw} onChange={e => setKw(e.target.value)} />
{isPending && <span>输入中...</span>}
</>
);
}
拓展思考
- 竞态升级:若接口返回顺序不确定,可在 useDebounce 内部维护一个 ref 版本号,在 fetch 返回后对比版本号,只采纳最新一次。
- 取消能力:把 clear 函数通过 ref 暴露给外部,父组件可主动取消等待中的副作用;或返回一个 cancel 方法。
- 立即调用选项:增加第三个参数 { leading: boolean, trailing: boolean },实现 lodash 级灵活度。
- 统一包:将 useDebounce、useThrottle、useInterval、useCountDown 等高频“时间类” Hooks 收敛到 @company/react-hooks,配合 changeset 发包,符合国内大中台共享库规范。
- 性能再优化:用 useRef 代替 useState 保存“是否稳定”标记,可彻底避免额外渲染;但需配合 useEvent 抹平回调,确保消费方拿到的 setState 永远最新。
- 测试覆盖:用 jest.useFakeTimers + RTL 写“快速输入 3 次,只触发 1 次接口”用例;写“组件卸载后不会 setState”用例,防止国内 CodeReview 被挑刺。