Skip to content

Instantly share code, notes, and snippets.

@Glidias
Last active March 23, 2022 10:51
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 Glidias/34ad697d31ccbb16fe05742cedfc96a6 to your computer and use it in GitHub Desktop.
Save Glidias/34ad697d31ccbb16fe05742cedfc96a6 to your computer and use it in GitHub Desktop.
useEffect hook that only triggers on subsequent renders when combined with useCallback
/**
* useEffect() that skips the first render execution before being mounted
* @param callback Important: A *Memomized* callback reference (eg. via `useCallback()`) or any other function
* to process/return a given lazy initialized state! eg. `usePostEffect(useCallback(.., [...]))`
* Callback will call again on next frame via useEffect() if callback method supplied is different from previous case,
* but on subsequent renders only.
*/
export function usePostEffect(callback: Function) {
const ref = useRef(false);
useEffect(() => {
if (ref.current) callback();
else ref.current = true;
}, [callback]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment