Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created April 18, 2022 00:03
Show Gist options
  • Save MarekZeman91/c493721c631f030b98a6f6a29e5d4082 to your computer and use it in GitHub Desktop.
Save MarekZeman91/c493721c631f030b98a6f6a29e5d4082 to your computer and use it in GitHub Desktop.
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