|
| 1 | +import Object from "@rbxts/object-utils"; |
| 2 | +import { TableToString } from "@rbxts/rbx-debug"; |
| 3 | +import { useEffect, useRef } from "@rbxts/react"; |
| 4 | +import { t } from "@rbxts/t"; |
| 5 | + |
| 6 | +interface ChangeObject { |
| 7 | + from: unknown; |
| 8 | + to: unknown; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * A simple hook that checks which prop caused the component to re-render. |
| 13 | + * |
| 14 | + * @param name - The name of the component. |
| 15 | + * @param props - The props of the component. |
| 16 | + * @param logFunction - The function to use to log the changes. |
| 17 | + * @param logEnabled - Whether or not to log the changes. |
| 18 | + * @see https://github.com/cool-organization/rbx-hooks/blob/main/src/debugging/use-why-did-you-update.ts |
| 19 | + */ |
| 20 | +export function useWhyDidYouUpdate( |
| 21 | + name: string, |
| 22 | + props: Record<string, unknown>, |
| 23 | + logFunction = print, |
| 24 | + logEnabled = true, |
| 25 | +): void { |
| 26 | + const previousProps = useRef<Record<string, unknown>>({}); |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + const previous = previousProps.current; |
| 30 | + |
| 31 | + const allKeys = Object.keys({ ...previous, ...props }); |
| 32 | + const changesObject: Record<string, ChangeObject> = {}; |
| 33 | + |
| 34 | + for (const key of allKeys) { |
| 35 | + let previousValue = previous[key]; |
| 36 | + let updatedValue = props[key]; |
| 37 | + |
| 38 | + if (previousValue !== updatedValue) { |
| 39 | + // We need to remove the meta tables from the previous and new |
| 40 | + // values to ensure we don't call any meta-methods on the props. |
| 41 | + if (t.table(previousValue)) { |
| 42 | + // eslint-disable-next-line ts/no-non-null-assertion -- Required to remove meta table |
| 43 | + previousValue = setmetatable(table.clone(previousValue), undefined!); |
| 44 | + } |
| 45 | + |
| 46 | + if (t.table(updatedValue)) { |
| 47 | + // eslint-disable-next-line ts/no-non-null-assertion -- Required to remove meta table |
| 48 | + updatedValue = setmetatable(table.clone(updatedValue), undefined!); |
| 49 | + } |
| 50 | + |
| 51 | + changesObject[key] = { |
| 52 | + from: previousValue, |
| 53 | + to: updatedValue, |
| 54 | + }; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + if (logEnabled && next(changesObject)[0]) { |
| 59 | + logFunction(name + " " + TableToString(changesObject, true)); |
| 60 | + } |
| 61 | + |
| 62 | + previousProps.current = props; |
| 63 | + }); |
| 64 | +} |
0 commit comments