nexo/apps/mattermost/app/hooks/why_did_you_update.ts

50 lines
2 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {useEffect, useRef} from 'react';
import {logInfo} from '@utils/log';
export function useWhyDidYouUpdate(name: string, props: any) {
// Get a mutable ref object where we can store props ...
// ... for comparison next time this hook runs.
const previousProps = useRef<any | undefined>(undefined);
const renderCount = useRef(0);
useEffect(() => {
renderCount.current += 1;
if (previousProps.current) {
// Get all keys from previous and current props
const allKeys = Object.keys({...previousProps.current, ...props});
// Use this object to keep track of changed props
const changesObj: any = {};
// Iterate through keys
allKeys.forEach((key) => {
// If previous is different from current
if (previousProps.current[key] !== props[key]) {
// Add to changesObj
changesObj[key] = {
from: previousProps.current[key],
to: props[key],
};
}
});
// If changesObj not empty then output to console
if (Object.keys(changesObj).length) {
logInfo(Date.now(), `[why-did-you-update] ${name} render #${renderCount.current}:`, JSON.stringify(Object.keys(changesObj)));
} else {
// IMPORTANT: Render happened but nothing changed!
logInfo(Date.now(), `[why-did-you-update] ${name} render #${renderCount.current}: NO CHANGES DETECTED (parent re-render)`);
}
} else {
logInfo(Date.now(), `[why-did-you-update] ${name} render #${renderCount.current}: INITIAL RENDER`);
}
// Finally update previousProps with current props for next hook call
previousProps.current = props;
});
}