Prevent a function from being called too many times React-Code Examples

Victor Talmacinschi

Prevent a function from being called too many times React

JavaScript by Victor Talmacinschi June 16, 2022

import React, { useState, useEffect } from 'react';

function useThrottle(fn, threshhold, scope) {
  let lastFnCallTimestamp = Date.now();

  return function throttleWrapper() {
    const now = Date.now();
    if (now - lastFnCallTimestamp < threshhold) return;

    lastFnCallTimestamp = now;
    fn.apply(scope, arguments);
  }
}

// Usage
function MyComponent() {
  const [clicks, setClicks] = useState(0);

  function handleClick() {
    setClicks(clicks + 1);
  }

  const throttledHandleClick = useThrottle(handleClick, 1000);

  return (
    <div onClick={throttledHandleClick}>
      This div has been clicked {clicks} times.
    </div>
  );
}

0

43.432

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories