From df810e12e09158524d791091b458871ab9ae8fd6 Mon Sep 17 00:00:00 2001 From: Sam Tsai Date: Wed, 2 Dec 2026 11:25:50 -0500 Subject: [PATCH 1/2] fix: detect inline props by content instead of timing in re-render warning The re-render warning used to fire whenever two updates happened within 60ms, which caused false positives on mount under React StrictMode (memo replays) and for props that genuinely change quickly, while missing inline props on slower re-renders. It now warns when a prop receives a new value with identical content (deep comparison, functions compared by source) on consecutive updates, names only the offending props, warns once per prop, and suggests how to fix it. Co-Authored-By: Claude Opus 5.5 --- doc-tools/doc-pages/src/pages/PageFAQ.tsx | 2 +- .../render/src/RenderHTMLConfigProvider.tsx | 5 +- packages/render/src/RenderHTMLSource.tsx | 7 +- .../src/context/RenderRegistryProvider.tsx | 4 +- .../src/context/RenderersPropsProvider.tsx | 5 +- .../src/hooks/__tests__/useProfiler.test.tsx | 160 +++++++++++++++++ packages/render/src/hooks/useProfiler.ts | 169 +++++++++++++++--- packages/render/src/hooks/useTRenderEngine.ts | 7 +- 8 files changed, 321 insertions(+), 38 deletions(-) create mode 100644 packages/render/src/hooks/__tests__/useProfiler.test.tsx diff --git a/doc-tools/doc-pages/src/pages/PageFAQ.tsx b/doc-tools/doc-pages/src/pages/PageFAQ.tsx index 6ab93f20..d7b8b9c1 100644 --- a/doc-tools/doc-pages/src/pages/PageFAQ.tsx +++ b/doc-tools/doc-pages/src/pages/PageFAQ.tsx @@ -110,7 +110,7 @@ export default function PageFAQ() { -
+
There is a detailed explaination for this warning here:{' '} diff --git a/packages/render/src/RenderHTMLConfigProvider.tsx b/packages/render/src/RenderHTMLConfigProvider.tsx index 925062a4..340984de 100644 --- a/packages/render/src/RenderHTMLConfigProvider.tsx +++ b/packages/render/src/RenderHTMLConfigProvider.tsx @@ -35,9 +35,10 @@ export default function RenderHTMLConfigProvider( ...sharedProps } = props; const engine = useAmbientTRenderEngine(); - const profile = useProfiler({ prop: 'remoteErrorView or remoteLoadingView' }); + const profile = useProfiler({}); const sourceLoaderConfig = useMemo(() => { - typeof __DEV__ === 'boolean' && __DEV__ && profile(); + typeof __DEV__ === 'boolean' && __DEV__ && + profile({ remoteErrorView, remoteLoadingView }); return { remoteErrorView: remoteErrorView || defaultRenderError, remoteLoadingView: remoteLoadingView || defaultRenderLoading diff --git a/packages/render/src/RenderHTMLSource.tsx b/packages/render/src/RenderHTMLSource.tsx index 2ededa7f..b2bac6b5 100644 --- a/packages/render/src/RenderHTMLSource.tsx +++ b/packages/render/src/RenderHTMLSource.tsx @@ -78,11 +78,10 @@ const RenderHTMLSource = memo( contentWidth, ...props }: RenderHTMLSourceProps) { - const profile = useProfiler({ - prop: 'onDocumentMetadataLoaded or onTTreeChange' - }); + const profile = useProfiler({}); const ttreeEvents: TTreeEvents = useMemo(() => { - typeof __DEV__ === 'boolean' && __DEV__ && profile(); + typeof __DEV__ === 'boolean' && __DEV__ && + profile({ onDocumentMetadataLoaded, onTTreeChange }); return { onDocumentMetadataLoaded, onTTreeChange diff --git a/packages/render/src/context/RenderRegistryProvider.tsx b/packages/render/src/context/RenderRegistryProvider.tsx index 0da8491e..036cdade 100644 --- a/packages/render/src/context/RenderRegistryProvider.tsx +++ b/packages/render/src/context/RenderRegistryProvider.tsx @@ -33,9 +33,9 @@ export default function RenderRegistryProvider({ elementModels: HTMLElementModelRecord; renderers?: CustomTagRendererRecord; }>) { - const profile = useProfiler({ prop: 'renderers' }); + const profile = useProfiler({}); const registry = useMemo(() => { - typeof __DEV__ === 'boolean' && __DEV__ && profile(); + typeof __DEV__ === 'boolean' && __DEV__ && profile({ renderers }); return new RenderRegistry(renderers, elementModels); }, [renderers, elementModels, profile]); return ( diff --git a/packages/render/src/context/RenderersPropsProvider.tsx b/packages/render/src/context/RenderersPropsProvider.tsx index 9a4cce92..aabe12d8 100644 --- a/packages/render/src/context/RenderersPropsProvider.tsx +++ b/packages/render/src/context/RenderersPropsProvider.tsx @@ -31,9 +31,10 @@ export function useRendererProps< export default function RenderersPropsProvider( props: PropsWithChildren ) { - const profile = useProfiler({ prop: 'renderersProps' }); + const profile = useProfiler({}); const mergedRenderersProps = useMemo(() => { - typeof __DEV__ === 'boolean' && __DEV__ && profile(); + typeof __DEV__ === 'boolean' && __DEV__ && + profile({ renderersProps: props.renderersProps }); return mergeDeepRight(defaultRendererProps, props.renderersProps || {}); }, [props.renderersProps, profile]); return React.createElement( diff --git a/packages/render/src/hooks/__tests__/useProfiler.test.tsx b/packages/render/src/hooks/__tests__/useProfiler.test.tsx new file mode 100644 index 00000000..0f85028b --- /dev/null +++ b/packages/render/src/hooks/__tests__/useProfiler.test.tsx @@ -0,0 +1,160 @@ +import React, { StrictMode } from 'react'; +import { render, renderHook } from '@testing-library/react-native'; +import RenderHTML from '../../RenderHTML'; +import { RenderHTMLProps } from '../../shared-types'; +import useProfiler, { hasSameContent } from '../useProfiler'; + +function getRerenderWarnings() { + return (console.warn as jest.Mock).mock.calls + .map(([m]) => m) + .filter((m) => typeof m === 'string' && m.startsWith('You seem to pass')); +} + +describe('hasSameContent', () => { + it('should compare nested plain objects and arrays structurally', () => { + expect( + hasSameContent({ p: { color: 'red' } }, { p: { color: 'red' } }) + ).toBe(true); + expect(hasSameContent([1, { a: 2 }], [1, { a: 2 }])).toBe(true); + expect( + hasSameContent({ p: { color: 'red' } }, { p: { color: 'blue' } }) + ).toBe(false); + expect(hasSameContent({ a: 1 }, { a: 1, b: 2 })).toBe(false); + expect(hasSameContent([1], { 0: 1 })).toBe(false); + }); + it('should consider functions with identical source equal', () => { + const make = () => () => 1; + expect(hasSameContent(make(), make())).toBe(true); + expect( + hasSameContent( + () => 1, + () => 2 + ) + ).toBe(false); + }); + it('should not inspect class instances', () => { + expect(hasSameContent(new Date(0), new Date(0))).toBe(false); + }); + it('should terminate on cyclic structures', () => { + const a: any = {}; + a.self = a; + const b: any = {}; + b.self = b; + expect(() => hasSameContent(a, b)).not.toThrow(); + }); +}); + +describe('useProfiler', () => { + beforeEach(() => { + console.warn = jest.fn(); + }); + + function setup() { + return renderHook(() => useProfiler({ name: 'Comp' })).result.current; + } + + it('should not warn when the same references are profiled (StrictMode replays)', () => { + const profile = setup(); + const renderers = {}; + for (let i = 0; i < 5; i++) { + profile({ renderers }); + } + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('should not warn when a value is recreated only once', () => { + const profile = setup(); + profile({ tagsStyles: { p: { color: 'red' } } }); + profile({ tagsStyles: { p: { color: 'red' } } }); + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('should not warn when content genuinely changes', () => { + const profile = setup(); + for (let i = 0; i < 5; i++) { + profile({ baseStyle: { opacity: i / 5 } }); + } + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('should warn once per prop, naming only recreated props', () => { + const profile = setup(); + const stable = () => {}; + for (let i = 0; i < 6; i++) { + profile({ + renderersProps: { a: { onPress() {} } }, + onTTreeChange: stable + }); + } + expect(console.warn).toHaveBeenCalledTimes(1); + const message = (console.warn as jest.Mock).mock.calls[0][0] as string; + expect(message).toContain( + 'a new "renderersProps" value with identical content to the "Comp" component' + ); + expect(message).toContain('useMemo or useCallback'); + expect(message).not.toContain('onTTreeChange'); + }); + + it('should list several recreated props in one warning', () => { + const profile = setup(); + for (let i = 0; i < 3; i++) { + profile({ a: {}, b: [], c: () => null }); + } + expect(console.warn).toHaveBeenCalledTimes(1); + const message = (console.warn as jest.Mock).mock.calls[0][0] as string; + expect(message).toContain('new "a", "b" and "c" values'); + }); +}); + +describe('RenderHTML re-render warnings', () => { + const source = { html: '

Hello

' }; + beforeEach(() => { + console.warn = jest.fn(); + }); + + function renderTimes( + getProps: (i: number) => Partial, + times: number + ) { + const { rerender } = render( + + + + ); + for (let i = 1; i < times; i++) { + rerender( + + + + ); + } + } + + it('should not warn on mount in StrictMode, even with inline props', () => { + renderTimes( + () => ({ renderers: {}, renderersProps: {}, tagsStyles: {} }), + 1 + ); + expect(getRerenderWarnings()).toEqual([]); + }); + + it('should warn about inline props on repeated re-renders', () => { + renderTimes(() => ({ tagsStyles: { p: { color: 'red' } } }), 4); + const warnings = getRerenderWarnings(); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('"tagsStyles"'); + expect(warnings[0]).toContain('"TRenderEngineProvider"'); + }); + + it('should not warn when props are stable across re-renders', () => { + const tagsStyles = { p: { color: 'red' } }; + const renderersProps = { a: { onPress() {} } }; + renderTimes(() => ({ tagsStyles, renderersProps }), 4); + expect(getRerenderWarnings()).toEqual([]); + }); + + it('should not warn when props genuinely change on re-renders', () => { + renderTimes((i) => ({ baseStyle: { fontSize: 10 + i } }), 4); + expect(getRerenderWarnings()).toEqual([]); + }); +}); diff --git a/packages/render/src/hooks/useProfiler.ts b/packages/render/src/hooks/useProfiler.ts index eba28daa..a8354aa8 100644 --- a/packages/render/src/hooks/useProfiler.ts +++ b/packages/render/src/hooks/useProfiler.ts @@ -1,36 +1,157 @@ import { useCallback, useRef } from 'react'; -import { identity } from 'ramda'; - -declare const performance: { now: () => number }; - -const useProfiler = - typeof __DEV__ === 'boolean' && __DEV__ && typeof performance === 'object' - ? function useProfiler({ name, prop }: { name?: string; prop?: string }) { - const lastUpdate = useRef(0); - const profile = useCallback( - function onUpdate() { - const now = performance.now(); - const diff = now - lastUpdate.current; - if (diff < 60) { + +/** + * Number of consecutive updates in which a prop must be recreated with + * identical content before warning. Requiring more than one avoids flagging + * a single coincidental recreation (or a StrictMode replay on mount). + */ +const RECREATIONS_BEFORE_WARNING = 2; + +/** + * Maximum nesting depth explored when comparing values. Deeper structures are + * compared by reference, which keeps the check cheap and safe with cycles. + */ +const MAX_DEPTH = 6; + +export type ProfiledValues = object; + +export type Profile = (values: ProfiledValues) => void; + +/** + * Structural equality where functions are considered equal when their source + * is identical, which is what happens when the same inline function is + * recreated on each render. + * + * @internal + */ +export function hasSameContent(a: unknown, b: unknown, depth = 0): boolean { + if (Object.is(a, b)) { + return true; + } + if (typeof a === 'function' && typeof b === 'function') { + return a.toString() === b.toString(); + } + if ( + depth >= MAX_DEPTH || + typeof a !== 'object' || + typeof b !== 'object' || + a === null || + b === null || + Object.getPrototypeOf(a) !== Object.getPrototypeOf(b) + ) { + return false; + } + const proto = Object.getPrototypeOf(a); + if (proto !== Object.prototype && proto !== Array.prototype) { + // Class instances (Date, RegExp, Map...) are not inspected. + return false; + } + const keysA = Object.keys(a as object); + const keysB = Object.keys(b as object); + if (keysA.length !== keysB.length) { + return false; + } + return keysA.every( + (key) => + Object.prototype.hasOwnProperty.call(b, key) && + hasSameContent( + (a as Record)[key], + (b as Record)[key], + depth + 1 + ) + ); +} + +function formatPropNames(names: string[]) { + const quoted = names.map((n) => `"${n}"`); + if (quoted.length === 1) { + return `a new ${quoted[0]} value`; + } + return `new ${quoted.slice(0, -1).join(', ')} and ${ + quoted[quoted.length - 1] + } values`; +} + +/** + * @internal + */ +export function getRerenderWarning({ + componentName, + props +}: { + componentName: string; + props: string[]; +}) { + return ( + `You seem to pass ${formatPropNames( + props + )} with identical content to the "${componentName}" component ` + + 'on every render, causing costly tree re-renders. ' + + 'This usually happens when an object, array or function is created inline during render. ' + + 'Declare it outside of your component, or memoize it with useMemo or useCallback. ' + + 'See https://stackoverflow.com/q/68966120/2779871' + ); +} + +const useProfiler: (config: { name?: string }) => Profile = + typeof __DEV__ === 'boolean' && __DEV__ + ? function useProfiler({ name }: { name?: string }) { + const state = useRef<{ + previous: Record | null; + recreations: Record; + warned: Set; + }>({ + previous: null, + recreations: {}, + warned: new Set() + }); + return useCallback( + function profile(values) { + const s = state.current; + const previous = s.previous; + const current = values as Record; + s.previous = current; + if (previous === null) { + return; + } + const toWarn: string[] = []; + for (const key of Object.keys(current)) { + if (Object.is(current[key], previous[key])) { + // Unchanged (or a StrictMode replay); keep the streak as is. + continue; + } + if (!hasSameContent(current[key], previous[key])) { + // A genuine change of value. + s.recreations[key] = 0; + continue; + } + s.recreations[key] = (s.recreations[key] || 0) + 1; + if ( + s.recreations[key] >= RECREATIONS_BEFORE_WARNING && + !s.warned.has(key) + ) { + s.warned.add(key); + toWarn.push(key); + } + } + if (toWarn.length) { console.warn( - `You seem to update ${ - prop ? `the ${prop} prop(s)` : 'props' - } of the "${ - name ? name : 'RenderHTML' - }" component in short periods of time, causing costly tree rerenders (last update was ${diff.toFixed( - 2 - )}ms ago). See https://stackoverflow.com/q/68966120/2779871` + getRerenderWarning({ + componentName: name || 'RenderHTML', + props: toWarn + }) ); } - lastUpdate.current = now; }, - [name, prop] + [name] ); - return profile; } : /* istanbul ignore next */ function useProfiler() { - return identity as () => void; + return noop; }; +/* istanbul ignore next */ +function noop() {} + export default useProfiler; diff --git a/packages/render/src/hooks/useTRenderEngine.ts b/packages/render/src/hooks/useTRenderEngine.ts index 3f5fec51..cb47bd29 100644 --- a/packages/render/src/hooks/useTRenderEngine.ts +++ b/packages/render/src/hooks/useTRenderEngine.ts @@ -57,8 +57,7 @@ export default function useTRenderEngine({ }: TRenderEngineConfig) { const profile = useProfiler({ name: 'TRenderEngineProvider' }); return useMemo(() => { - typeof __DEV__ === 'boolean' && __DEV__ && profile(); - return buildTREFromConfig({ + const config: TRenderEngineConfig = { allowedStyles, baseStyle, classesStyles, @@ -79,7 +78,9 @@ export default function useTRenderEngine({ setMarkersForTNode, systemFonts, tagsStyles - }); + }; + typeof __DEV__ === 'boolean' && __DEV__ && profile(config); + return buildTREFromConfig(config); }, [ profile, allowedStyles, From a3e6438e3c545adc9536b9c13e1ff457b7bd75ab Mon Sep 17 00:00:00 2001 From: Sam Tsai Date: Wed, 2 Dec 2026 11:34:54 -0500 Subject: [PATCH 2/2] fix: keep re-render warning helpers out of production bundles The comparison and message helpers lived at module level and were exported, so minifiers could not drop them when __DEV__ is false. They now live inside the dev-only branch, and the production build of the hook is just a no-op. Co-Authored-By: Claude Opus 5.5 --- .../src/hooks/__tests__/useProfiler.test.tsx | 76 ++--- packages/render/src/hooks/useProfiler.ts | 269 +++++++++--------- 2 files changed, 174 insertions(+), 171 deletions(-) diff --git a/packages/render/src/hooks/__tests__/useProfiler.test.tsx b/packages/render/src/hooks/__tests__/useProfiler.test.tsx index 0f85028b..968dea62 100644 --- a/packages/render/src/hooks/__tests__/useProfiler.test.tsx +++ b/packages/render/src/hooks/__tests__/useProfiler.test.tsx @@ -2,7 +2,7 @@ import React, { StrictMode } from 'react'; import { render, renderHook } from '@testing-library/react-native'; import RenderHTML from '../../RenderHTML'; import { RenderHTMLProps } from '../../shared-types'; -import useProfiler, { hasSameContent } from '../useProfiler'; +import useProfiler from '../useProfiler'; function getRerenderWarnings() { return (console.warn as jest.Mock).mock.calls @@ -10,40 +10,6 @@ function getRerenderWarnings() { .filter((m) => typeof m === 'string' && m.startsWith('You seem to pass')); } -describe('hasSameContent', () => { - it('should compare nested plain objects and arrays structurally', () => { - expect( - hasSameContent({ p: { color: 'red' } }, { p: { color: 'red' } }) - ).toBe(true); - expect(hasSameContent([1, { a: 2 }], [1, { a: 2 }])).toBe(true); - expect( - hasSameContent({ p: { color: 'red' } }, { p: { color: 'blue' } }) - ).toBe(false); - expect(hasSameContent({ a: 1 }, { a: 1, b: 2 })).toBe(false); - expect(hasSameContent([1], { 0: 1 })).toBe(false); - }); - it('should consider functions with identical source equal', () => { - const make = () => () => 1; - expect(hasSameContent(make(), make())).toBe(true); - expect( - hasSameContent( - () => 1, - () => 2 - ) - ).toBe(false); - }); - it('should not inspect class instances', () => { - expect(hasSameContent(new Date(0), new Date(0))).toBe(false); - }); - it('should terminate on cyclic structures', () => { - const a: any = {}; - a.self = a; - const b: any = {}; - b.self = b; - expect(() => hasSameContent(a, b)).not.toThrow(); - }); -}); - describe('useProfiler', () => { beforeEach(() => { console.warn = jest.fn(); @@ -95,6 +61,46 @@ describe('useProfiler', () => { expect(message).not.toContain('onTTreeChange'); }); + it('should compare nested objects and arrays by content', () => { + const profile = setup(); + for (let i = 0; i < 3; i++) { + profile({ tagsStyles: { p: { color: 'red' } }, list: [1, { a: 2 }] }); + } + expect(console.warn).toHaveBeenCalledTimes(1); + const message = (console.warn as jest.Mock).mock.calls[0][0] as string; + expect(message).toContain('new "tagsStyles" and "list" values'); + }); + + it('should treat functions with different source as genuine changes', () => { + const profile = setup(); + profile({ onPress: () => 1 }); + profile({ onPress: () => 2 }); + profile({ onPress: () => 3 }); + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('should not inspect class instances', () => { + const profile = setup(); + for (let i = 0; i < 3; i++) { + profile({ date: new Date(0) }); + } + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('should terminate on cyclic structures', () => { + const profile = setup(); + const makeCyclic = () => { + const o: any = {}; + o.self = o; + return o; + }; + expect(() => { + for (let i = 0; i < 3; i++) { + profile({ cyclic: makeCyclic() }); + } + }).not.toThrow(); + }); + it('should list several recreated props in one warning', () => { const profile = setup(); for (let i = 0; i < 3; i++) { diff --git a/packages/render/src/hooks/useProfiler.ts b/packages/render/src/hooks/useProfiler.ts index a8354aa8..9d55466c 100644 --- a/packages/render/src/hooks/useProfiler.ts +++ b/packages/render/src/hooks/useProfiler.ts @@ -1,151 +1,148 @@ import { useCallback, useRef } from 'react'; -/** - * Number of consecutive updates in which a prop must be recreated with - * identical content before warning. Requiring more than one avoids flagging - * a single coincidental recreation (or a StrictMode replay on mount). - */ -const RECREATIONS_BEFORE_WARNING = 2; - -/** - * Maximum nesting depth explored when comparing values. Deeper structures are - * compared by reference, which keeps the check cheap and safe with cycles. - */ -const MAX_DEPTH = 6; - export type ProfiledValues = object; export type Profile = (values: ProfiledValues) => void; -/** - * Structural equality where functions are considered equal when their source - * is identical, which is what happens when the same inline function is - * recreated on each render. - * - * @internal - */ -export function hasSameContent(a: unknown, b: unknown, depth = 0): boolean { - if (Object.is(a, b)) { - return true; - } - if (typeof a === 'function' && typeof b === 'function') { - return a.toString() === b.toString(); - } - if ( - depth >= MAX_DEPTH || - typeof a !== 'object' || - typeof b !== 'object' || - a === null || - b === null || - Object.getPrototypeOf(a) !== Object.getPrototypeOf(b) - ) { - return false; - } - const proto = Object.getPrototypeOf(a); - if (proto !== Object.prototype && proto !== Array.prototype) { - // Class instances (Date, RegExp, Map...) are not inspected. - return false; - } - const keysA = Object.keys(a as object); - const keysB = Object.keys(b as object); - if (keysA.length !== keysB.length) { - return false; - } - return keysA.every( - (key) => - Object.prototype.hasOwnProperty.call(b, key) && - hasSameContent( - (a as Record)[key], - (b as Record)[key], - depth + 1 - ) - ); -} +const useProfiler: (config: { name?: string }) => Profile = + typeof __DEV__ === 'boolean' && __DEV__ + ? (function () { + /** + * Number of consecutive updates in which a prop must be recreated with + * identical content before warning. Requiring more than one avoids flagging + * a single coincidental recreation (or a StrictMode replay on mount). + */ + const RECREATIONS_BEFORE_WARNING = 2; + + /** + * Maximum nesting depth explored when comparing values. Deeper structures are + * compared by reference, which keeps the check cheap and safe with cycles. + */ + const MAX_DEPTH = 6; -function formatPropNames(names: string[]) { - const quoted = names.map((n) => `"${n}"`); - if (quoted.length === 1) { - return `a new ${quoted[0]} value`; - } - return `new ${quoted.slice(0, -1).join(', ')} and ${ - quoted[quoted.length - 1] - } values`; -} + /** + * Structural equality where functions are considered equal when their source + * is identical, which is what happens when the same inline function is + * recreated on each render. + */ + function hasSameContent(a: unknown, b: unknown, depth = 0): boolean { + if (Object.is(a, b)) { + return true; + } + if (typeof a === 'function' && typeof b === 'function') { + return a.toString() === b.toString(); + } + if ( + depth >= MAX_DEPTH || + typeof a !== 'object' || + typeof b !== 'object' || + a === null || + b === null || + Object.getPrototypeOf(a) !== Object.getPrototypeOf(b) + ) { + return false; + } + const proto = Object.getPrototypeOf(a); + if (proto !== Object.prototype && proto !== Array.prototype) { + // Class instances (Date, RegExp, Map...) are not inspected. + return false; + } + const keysA = Object.keys(a as object); + const keysB = Object.keys(b as object); + if (keysA.length !== keysB.length) { + return false; + } + return keysA.every( + (key) => + Object.prototype.hasOwnProperty.call(b, key) && + hasSameContent( + (a as Record)[key], + (b as Record)[key], + depth + 1 + ) + ); + } -/** - * @internal - */ -export function getRerenderWarning({ - componentName, - props -}: { - componentName: string; - props: string[]; -}) { - return ( - `You seem to pass ${formatPropNames( - props - )} with identical content to the "${componentName}" component ` + - 'on every render, causing costly tree re-renders. ' + - 'This usually happens when an object, array or function is created inline during render. ' + - 'Declare it outside of your component, or memoize it with useMemo or useCallback. ' + - 'See https://stackoverflow.com/q/68966120/2779871' - ); -} + function formatPropNames(names: string[]) { + const quoted = names.map((n) => `"${n}"`); + if (quoted.length === 1) { + return `a new ${quoted[0]} value`; + } + return `new ${quoted.slice(0, -1).join(', ')} and ${ + quoted[quoted.length - 1] + } values`; + } -const useProfiler: (config: { name?: string }) => Profile = - typeof __DEV__ === 'boolean' && __DEV__ - ? function useProfiler({ name }: { name?: string }) { - const state = useRef<{ - previous: Record | null; - recreations: Record; - warned: Set; - }>({ - previous: null, - recreations: {}, - warned: new Set() - }); - return useCallback( - function profile(values) { - const s = state.current; - const previous = s.previous; - const current = values as Record; - s.previous = current; - if (previous === null) { - return; - } - const toWarn: string[] = []; - for (const key of Object.keys(current)) { - if (Object.is(current[key], previous[key])) { - // Unchanged (or a StrictMode replay); keep the streak as is. - continue; + function getRerenderWarning({ + componentName, + props + }: { + componentName: string; + props: string[]; + }) { + return ( + `You seem to pass ${formatPropNames( + props + )} with identical content to the "${componentName}" component ` + + 'on every render, causing costly tree re-renders. ' + + 'This usually happens when an object, array or function is created inline during render. ' + + 'Declare it outside of your component, or memoize it with useMemo or useCallback. ' + + 'See https://stackoverflow.com/q/68966120/2779871' + ); + } + + return function useDevProfiler({ name }: { name?: string }) { + const state = useRef<{ + previous: Record | null; + recreations: Record; + warned: Set; + }>({ + previous: null, + recreations: {}, + warned: new Set() + }); + return useCallback( + function profile(values) { + const s = state.current; + const previous = s.previous; + const current = values as Record; + s.previous = current; + if (previous === null) { + return; } - if (!hasSameContent(current[key], previous[key])) { - // A genuine change of value. - s.recreations[key] = 0; - continue; + const toWarn: string[] = []; + for (const key of Object.keys(current)) { + if (Object.is(current[key], previous[key])) { + // Unchanged (or a StrictMode replay); keep the streak as is. + continue; + } + if (!hasSameContent(current[key], previous[key])) { + // A genuine change of value. + s.recreations[key] = 0; + continue; + } + s.recreations[key] = (s.recreations[key] || 0) + 1; + if ( + s.recreations[key] >= RECREATIONS_BEFORE_WARNING && + !s.warned.has(key) + ) { + s.warned.add(key); + toWarn.push(key); + } } - s.recreations[key] = (s.recreations[key] || 0) + 1; - if ( - s.recreations[key] >= RECREATIONS_BEFORE_WARNING && - !s.warned.has(key) - ) { - s.warned.add(key); - toWarn.push(key); + if (toWarn.length) { + console.warn( + getRerenderWarning({ + componentName: name || 'RenderHTML', + props: toWarn + }) + ); } - } - if (toWarn.length) { - console.warn( - getRerenderWarning({ - componentName: name || 'RenderHTML', - props: toWarn - }) - ); - } - }, - [name] - ); - } + }, + [name] + ); + }; + })() : /* istanbul ignore next */ function useProfiler() { return noop;