Created
April 18, 2022 00:03
-
-
Save MarekZeman91/c493721c631f030b98a6f6a29e5d4082 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { DependencyList, EffectCallback, useRef } from 'react'; | |
import { useOnComponentUnmount } from './useOnComponentUnmount'; | |
const arrayMatch = (arr1?: DependencyList, arr2?: DependencyList) => { | |
if (!arr1 || !arr2) return false; | |
if (arr1.length !== arr2.length) return false; | |
return arr1.every((_, i) => arr1[i] === arr2[i]); | |
}; | |
export const useImmediateEffect = (effect: EffectCallback, deps?: DependencyList) => { | |
const cleanRef = useRef<() => void>(() => {}); | |
const depsRef = useRef<DependencyList>(); | |
if (!depsRef.current || !arrayMatch(depsRef.current, deps)) { | |
depsRef.current = deps; | |
cleanRef.current(); | |
cleanRef.current = effect() || (() => {}); | |
} | |
useOnComponentUnmount(() => cleanRef.current()); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment