Created
November 2, 2022 11:58
-
-
Save lukKowalski/97534f8f9e1c8a6c82c8f024d84bb8ac 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
const useControlledEffect = (callback, dependenciesArray) => { | |
const controlRef = useRef(false); | |
const stopFunc = () => { | |
controlRef.current = true; | |
}; | |
const wrappedCallback = (params = []) => { | |
callback(stopFunc, controlRef.current, ...params); | |
}; | |
useEffect.apply( | |
this, | |
dependenciesArray ? [wrappedCallback, dependenciesArray] : [wrappedCallback] | |
); | |
}; | |
//HOW TO USE: | |
useControlledEffect((stop, isStopped) => { | |
// do some custom actions | |
if (!isStopped) { | |
// do some custom actions | |
stop(); //calling this will change isStopped to true | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment