常用react hooks收集
1. useDebounce
function userDebounce(fn,delay,deps=[]){ let {current} = useRef({fn, timer: null}) setEffect(() => { current.fn = fn; },[fn]); return userCallback(function(...args){ if(current.timer) clearTimeout(crurent.timer); current.timer = setTimeout(() => { current.fn.call(this,...args); },delay); },deps); }
2. useThrottle
function useThrottle(fn,interval){ let {current} = useRef({fn,timer:null}); setEffect(() => { current.fn = fn; },[fn]) return useCallback(function(...args){ if(!current.timer){ current.timer = setTimeout(() => { delete current.tiemer; },interval); current.fn.call(this,...args); } },deps); }
3. useScrollPos
//eleRef是用useRef获得的React元素引用 function useScrollPos(eleRef){ const [pos,setPos] = useState([0,0]); useEffect(() => { function onScroll)(){ setPos([eleRef.current.scrollLeft,eleRef.current.scrollTop]); } eleRef.current.addEventListener('scroll', onScroll); return () => { eleRef.current.removeEvenlistener('scroll',onScroll); } },[]); return pos; }
4. useTitle
function useTitle(title){ setEffect(() => { document.tilte = title; },[]) }
5. useWinSize
function useWinSize() { const [size, setSize] = useState({ width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }) const onResize = useCallback(() => { setSize({ width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }) }, []) useEffect(() => { window.addEventListener('resize', onResize) return () => { window.removeEventListener('reisze', onResize) } }, []) return size }
6. useInterval
//相比setInterval, useInterval就一个用处,delay可以动态修改 function useInterval(callback, delay) { const savedCallback = useRef(); useEffect(() => { savedCallback.current = callback; }); useEffect(() => { function tick() { savedCallback.current(); } let id = setInterval(tick, delay); return () => clearInterval(id); }, [delay]); }
参考:https://juejin.im/post/6854573217349107725
https://zhuanlan.zhihu.com/p/61944308
https://www.imooc.com/article/301277
https://juejin.im/post/6850037283535880205
https://www.cnblogs.com/qcloud1001/p/10408634.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具