Last active
July 31, 2022 18:13
-
-
Save dr-skot/0a3b6aeaa61939005017ce3352797401 to your computer and use it in GitHub Desktop.
run an effect when the dependencies change, but not at initialization
This file contains 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
import { useEffect, useRef, EffectCallback, DependencyList } from 'react'; | |
// React.useEffect runs its effect 1) at initialization and then 2) whenever the deps change | |
// Sometimes you don't want (1), just (2). That's what this is for. | |
export function useEffectOnMount(effect: EffectCallback, deps: DependencyList): void { | |
const isMounted = useRef(false); | |
useEffect(() => { | |
if (isMounted.current) return effect(); | |
else isMounted.current = true; | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, deps); | |
useEffect(() => { | |
return () => isMounted.current = false; | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment