@zohodesk/hooks
Version:
Unified Component Library - Hooks
28 lines (24 loc) • 980 B
JavaScript
import { useEffect, useRef } from 'react';
/**
* https://www.perssondennis.com/articles/react-hook-use-run-once?fs=e&s=cl
* @param {*} callback
* @param {*} conditions
*/
// This hook is as same as useEffect. But, will not execute the callback on mount (Initial Render).
export default function useEffectCallOnlyAfterState(callback) {
let conditions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
let cleanUpFunction = arguments.length > 2 ? arguments[2] : undefined;
const currentRef = useRef(false);
useEffect(() => {
let returnValue;
if (!currentRef.current) {
currentRef.current = true;
} else {
callback && (returnValue = callback());
if (typeof returnValue === 'function') {
console.warn('Tip: If you are trying to perform a cleanup function, please send it as the third argument');
}
}
return () => typeof cleanUpFunction === 'function' && cleanUpFunction();
}, conditions);
}