File size: 842 Bytes
24d8b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useCallback, useEffect, useRef } from "react";

export default function useDebounce() {
  // Using a ref to store the current timeout identifier
  // This is to ensure it persists across renders without causing re-renders
  const timeoutRef = useRef(null);

  // The debounce function
  const debounce = useCallback((func, wait) => {
    // Clear any existing timeout to ensure only the latest call is executed
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    // Set the new timeout
    timeoutRef.current = setTimeout(() => {
      func();
    }, wait);
  }, []);

  // Cleanup function to clear the timeout when the component is unmounted
  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  return debounce;
}