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