Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Last active March 21, 2022 17:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Muzietto/c8822805231a90c2a13edb9b80f8bb85 to your computer and use it in GitHub Desktop.
Save Muzietto/c8822805231a90c2a13edb9b80f8bb85 to your computer and use it in GitHub Desktop.
useDelayedEffect - using setTimeout in React functional components (custom hook)
import { useEffect, useRef } from 'react';
function useDelayedEffect(effect, changingStateVars = [], delay = 1000) {
const mutable = useRef();
const delayedEffect = () => {
mutable.current = setTimeout(effect, delay);
return () => {
clearTimeout(mutable.current);
};
};
useEffect(delayedEffect, changingStateVars);
}
export default useDelayedEffect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment