Created
February 2, 2024 15:39
-
-
Save l-portet/25617a0b0942848f686f9a6481f7b556 to your computer and use it in GitHub Desktop.
This file contains 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, 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