Skip to content

Instantly share code, notes, and snippets.

@dggodfrey
Created April 23, 2021 23:17
Show Gist options
  • Save dggodfrey/1389f405a8fb697991a7dfcaf562ac88 to your computer and use it in GitHub Desktop.
Save dggodfrey/1389f405a8fb697991a7dfcaf562ac88 to your computer and use it in GitHub Desktop.
import {useEffect, useRef, EffectCallback, DependencyList} from 'react';
type useNonInitialEffectReturn = void | (() => void | undefined)
export const useNonInitialEffect = (effect: EffectCallback, deps?: DependencyList): useNonInitialEffectReturn => {
const initialRender = useRef(true);
useEffect(() => {
let effectReturns: useNonInitialEffectReturn = () => { /* Empty Return fallback */ };
if (initialRender.current) {
initialRender.current = false;
} else {
effectReturns = effect();
}
if (effectReturns && typeof effectReturns === 'function') {
return effectReturns;
}
}, deps);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment