Skip to content

Instantly share code, notes, and snippets.

@rohmanhm
Last active May 6, 2024 12:28
Show Gist options
  • Save rohmanhm/075af264eb522779a2b03e37d9756135 to your computer and use it in GitHub Desktop.
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.
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