Skip to content

Instantly share code, notes, and snippets.

@lukebrandonfarrell
Last active June 12, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukebrandonfarrell/7e3162bd295b6f235a8c0881d8413e57 to your computer and use it in GitHub Desktop.
Save lukebrandonfarrell/7e3162bd295b6f235a8c0881d8413e57 to your computer and use it in GitHub Desktop.
Use an effect after the component has been mounted.
/**
* Use effect after component mount
*
* @param effect
* @param deps
*
* @return {*}
*/
export function useEffectAfterMount(effect, deps) {
const isFirstRun = useRef(true);
useEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
if (effect) return effect();
}, deps);
}
@alessioprestileo
Copy link

This could be improved by replacing line 18 with
if (effect) return effect();
This way, if effect returns a cleanup function, such function will be executed.

@lukebrandonfarrell
Copy link
Author

@alessioprestileo good point !

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