Skip to content

Instantly share code, notes, and snippets.

@l-portet
Created February 2, 2024 15:39
Show Gist options
  • Save l-portet/25617a0b0942848f686f9a6481f7b556 to your computer and use it in GitHub Desktop.
Save l-portet/25617a0b0942848f686f9a6481f7b556 to your computer and use it in GitHub Desktop.
import { DependencyList, EffectCallback, useEffect, useRef } from 'react';
export const useEffectWhen = (callback: EffectCallback, whatDeps: DependencyList, whenDeps: DependencyList) => {
const prevWhenValuesRef = useRef<DependencyList>([]);
useEffect(() => {
const prevWhenDeps = prevWhenValuesRef.current;
prevWhenValuesRef.current = whenDeps;
for (let i = 0; i < whenDeps.length; i++) {
if (!Object.is(prevWhenDeps[i], whenDeps[i])) {
callback();
return;
}
}
}, [...whatDeps, ...whenDeps]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment