Skip to content

Instantly share code, notes, and snippets.

@PaulRBerg
Last active November 30, 2019 17:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulRBerg/8a249e5b7608c018607c63437772eba1 to your computer and use it in GitHub Desktop.
Save PaulRBerg/8a249e5b7608c018607c63437772eba1 to your computer and use it in GitHub Desktop.
Custom Hook for delaying side effects declaratively
function useEffectWithDelay({ condition = false, func = () => {}, delay = 1000 }) {
useEffect(() => {
if (condition) {
const timeout = setTimeout(func, delay);
return () => {
clearTimeout(timeout);
};
}
return undefined;
}, [condition, delay, func]);
}
@PaulRBerg
Copy link
Author

You can now also find this in the npm registry, as part of the @paulrberg/react-hooks package. Install it as usual: yarn add @paulrberg/react-hooks or npm install @paulrberg/react-hooks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment