Published on

useThroattle Hook React

useThroattle Hook React

useThroattle Hook React

useThroattle Code and Usage

useThroattle is a hook to Throttle or limit the execution of a function.

import { useState, useEffect } from "react";

const useThrottle = (value, delay) => {
  const [throttledValue, setThrottledValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setThrottledValue(value);
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);

  return throttledValue;
};

// Usage in a component
function App() {
  const [scrollPosition, setScrollPosition] = useState(0);

  const handleScroll = () => {
    setScrollPosition(window.scrollY);
  };

  // Throttle the scroll event using the useThrottle hook
  const throttledScrollPosition = useThrottle(scrollPosition, 300);

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <div className="App">
      <h1>Throttle Example</h1>
      <p>Scroll position (throttled): {throttledScrollPosition}</p>
    </div>
  );
}

export default App;