beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
21 lines (20 loc) • 731 B
JavaScript
import { useLayoutEffect, useRef } from 'react';
import isFunction from './shared/isFunction';
import createHandlerSetter from './factory/createHandlerSetter';
/**
* Returns a callback setter for a callback to be performed when the component will unmount.
*/
const useWillUnmount = (callback) => {
const mountRef = useRef(false);
const [handler, setHandler] = createHandlerSetter(callback);
useLayoutEffect(() => {
mountRef.current = true;
return () => {
if (isFunction(handler === null || handler === void 0 ? void 0 : handler.current) && mountRef.current) {
handler.current();
}
};
}, []);
return setHandler;
};
export default useWillUnmount;