Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Last active July 31, 2022 18:13
Show Gist options
  • Save dr-skot/0a3b6aeaa61939005017ce3352797401 to your computer and use it in GitHub Desktop.
Save dr-skot/0a3b6aeaa61939005017ce3352797401 to your computer and use it in GitHub Desktop.
run an effect when the dependencies change, but not at initialization
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