Last active
June 12, 2020 14:43
-
-
Save lukebrandonfarrell/7e3162bd295b6f235a8c0881d8413e57 to your computer and use it in GitHub Desktop.
Use an effect after the component has been mounted.
This file contains hidden or 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
/** | |
* 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.