React 自定义hook 之 防抖和节流
一、简介
防抖和节流主要用于控制事件触发频率,提高页面性能和用户体验。
防抖: 当事件被触发后,在一定时间内有新的对应事件,则会取消老的事件执行。
节流: 当事件触发后,在一定时间内会忽略新的事件执行。
二、技术实现
1、useDebounce hook
export const useDebounce = (state, delay) => {
const [debounceState, setDebounceState] = useState({...state});
useEffect(() => {
const timeout = setTimeout(() => {
setDebounceParam({
...param,
});
}, delay);
return () => clearTimeout(timeout);
}, [state]);
}
使用样例:
export UserComponent = ()=>{
const [userName, setUserName] = useState("");
const [user, setUser] = useState({});
const debounceUserName = useDebounce(userName, 300);
useEffect(() => {
User user = getUserByUserName(userName);
setUser(...user);
}, [debounceUserName]);
return (
<div>
用户名:<input type = 'text' value = {userName} onChange = {setUserName}/>
用户信息: <span>{user.info}</span>
<div/>
);
}
2.useThrottle hook
export const useThrottle = (state, limit) =>{
const [throttleState, setThrottleState] = useState(...state);
// 记录下上次触发的时间
const [lastTrigger, setLastTrigger] = useState(Date.now());
useEffect(() => {
const timeout = setTimeOut(() =>{
if (Date.now() - lastTrigger < dealy){
return;
}
setThrottleState(throttleState);
setLastTrigger(now);
});
return clearTimeout(timeout);
}, [state])
}