| 1 |
import { useRef, useEffect, useState } from '@wordpress/element' |
| 2 |
|
| 3 |
export function useIsMounted() { |
| 4 |
const isMounted = useRef(false) |
| 5 |
|
| 6 |
useEffect(() => { |
| 7 |
isMounted.current = true |
| 8 |
return () => (isMounted.current = false) |
| 9 |
}) |
| 10 |
return isMounted |
| 11 |
} |
| 12 |
|
| 13 |
export const useIsDevMode = () => { |
| 14 |
const [devMode, setDevMode] = useState(false) |
| 15 |
const check = () => { |
| 16 |
return ( |
| 17 |
window.location.search.indexOf('DEVMODE') > -1 || |
| 18 |
window.location.search.indexOf('LOCALMODE') > -1 |
| 19 |
) |
| 20 |
} |
| 21 |
useEffect(() => { |
| 22 |
const handle = () => setDevMode(check()) |
| 23 |
handle() |
| 24 |
window.addEventListener('popstate', handle) |
| 25 |
return () => { |
| 26 |
window.removeEventListener('popstate', handle) |
| 27 |
} |
| 28 |
}, []) |
| 29 |
return devMode |
| 30 |
} |
| 31 |
|
| 32 |
/** Dev debugging tool to identify leaky renders: https://usehooks.com/useWhyDidYouUpdate/ */ |
| 33 |
export const useWhyDidYouUpdate = (name, props) => { |
| 34 |
const previousProps = useRef() |
| 35 |
useEffect(() => { |
| 36 |
if (previousProps.current) { |
| 37 |
const allKeys = Object.keys({ ...previousProps.current, ...props }) |
| 38 |
const changesObj = {} |
| 39 |
allKeys.forEach((key) => { |
| 40 |
if (previousProps.current[key] !== props[key]) { |
| 41 |
changesObj[key] = { |
| 42 |
from: previousProps.current[key], |
| 43 |
to: props[key], |
| 44 |
} |
| 45 |
} |
| 46 |
}) |
| 47 |
if (Object.keys(changesObj).length) { |
| 48 |
console.log('[why-did-you-update]', name, changesObj) |
| 49 |
} |
| 50 |
} |
| 51 |
previousProps.current = props |
| 52 |
}) |
| 53 |
} |
| 54 |
|