常用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

posted @   全玉  阅读(712)  评论(0编辑  收藏  举报
编辑推荐:
· 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工具
点击右上角即可分享
微信分享提示