Spaces:
Sleeping
Sleeping
| 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; | |
| } | |