Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Last active March 11, 2021 14:02
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 joepuzzo/4544d77a635d002aa631c6aa3ada77ff to your computer and use it in GitHub Desktop.
Save joepuzzo/4544d77a635d002aa631c6aa3ada77ff to your computer and use it in GitHub Desktop.
import { useRef, useEffect } from 'react';
// https://reactjs.org/docs/hooks-faq.html#can-i-run-an-effect-only-on-updates
/**
*
* Acts as a react useEffect that does not run on first render.
*
* @example
* useUpdateEffect(()=>{...}, [foo])
* 1st Render: NO CALL
* foo changes: GETS CALLED
*
*/
const useUpdateEffect = (effect, deps) => {
const firstRef = useRef(true);
const isFirstMount = firstRef.current;
useEffect(() => {
if (!isFirstMount) {
return effect();
} else {
firstRef.current = false;
}
}, deps);
};
export default useUpdateEffect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment