Skip to content

Instantly share code, notes, and snippets.

@lukKowalski
Created November 2, 2022 11:58
Show Gist options
  • Save lukKowalski/97534f8f9e1c8a6c82c8f024d84bb8ac to your computer and use it in GitHub Desktop.
Save lukKowalski/97534f8f9e1c8a6c82c8f024d84bb8ac to your computer and use it in GitHub Desktop.
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