Last active
May 6, 2024 12:28
-
-
Save rohmanhm/075af264eb522779a2b03e37d9756135 to your computer and use it in GitHub Desktop.
useDebouncedEffect to delay the React.useEffect to immediately being executed. It is useful to save some performance while user changing the state of the component.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DependencyList, useEffect } from 'react'; | |
export function useDebouncedEffect( | |
fn: () => void, | |
deps: DependencyList, | |
delay: number | |
) { | |
useEffect(() => { | |
const timer = setTimeout(() => { | |
fn(); | |
}, delay); | |
return () => { | |
clearTimeout(timer); | |
}; | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, deps); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment