自定义hook实现防抖节流

防抖:

export const useDebounce = (fn, delay = 500, dep = []) => {
  const { current } = useRef({ fn, timer: null });
  useEffect(function () {
    current.fn = fn;
  }, [fn]);
  return useCallback(function f(...args) {
    if (current.timer) {
      clearTimeout(current.timer);
    }
    current.timer = setTimeout(() => {
      current.fn.call(this, ...args);
    }, delay);
  }, dep)
}

节流:

export function useThrottle(fn, delay = 500, dep = []) {
  const { current } = useRef({ fn, timer: null })
  useEffect(function () {
    current.fn = fn
  }, [fn])

  return useCallback(function f(...args) {
    if (!current.timer) {
      current.timer = setTimeout(() => {
        delete current.timer
      }, delay)
      current.fn.call(this, ...args)
    }
  }, dep)
}

使用:

	import { useDebounce, useThrottle } from '...'
	const handleSearch = useDebounce(() => {
		// todo something
	}, 300)

	
	const handleScroll = useThrottle(() => {
		// todo something
	}, 1500)}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
react自定义hook实现非常简单。你只需要将常规的函数和逻辑包装在一个名称以 use 开头的函数里面,就可以将其作为自定义 hook 使用。例如,下面是一个 useEffect 自定义 hook 的示例代码: ``` import React, { useState, useEffect } from 'react'; function useCustomHook(myValue) { const [count, setCount] = useState(0); useEffect(() => { console.log(`my value is: ${myValue}`); console.log(`count is: ${count}`); }, [count, myValue]); function handlePlus() { setCount(count + 1); } function handleMinus() { setCount(count - 1); } return { count, handlePlus, handleMinus, }; } ``` 在这里,我们创建了一个名为 useCustomHook 的函数。该函数接受一个名为 myValue 的参数。我们在 useCustomHook 函数中使用 useState 和 useEffect。我们返回一个对象,该对象包含 count 值以及处理加法和减法的函数。 接下来,您可以将 useCustomHook 导入包含您的 react 程序的文件,并使用对它调用以前定义的函数来调用它。例如: ``` import React from 'react'; import { useCustomHook } from './useCustomHook'; function App() { const { count, handlePlus, handleMinus } = useCustomHook('my value'); return ( <div> <p>Count is: {count}</p> <button onClick={handlePlus}>Plus</button> <button onClick={handleMinus}>Minus</button> </div> ); } export default App; ``` 在这里,我们导入 useCustomHook,然后从调用它的返回对象中提取 count、处理加法和减法的函数。 这就是一个简单的自定义 hook 的范例。你可以创建任意数量的自定义 hook,从而封装 React 组件中的常见逻辑和代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值