Skip to content

Commit

Permalink
Merge branch 'main' into fix/jsx-source-debug-warning
Browse files Browse the repository at this point in the history
  • Loading branch information
rschristian authored Apr 27, 2024
2 parents 2e2f5ab + 613cacc commit 50c3f3e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
20 changes: 20 additions & 0 deletions debug/src/debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,31 @@ export function initDebug() {
if (oldBeforeDiff) oldBeforeDiff(vnode);
};

let renderCount = 0;
let currentComponent;
options._render = vnode => {
if (oldRender) {
oldRender(vnode);
}
hooksAllowed = true;

const nextComponent = vnode._component;
if (nextComponent === currentComponent) {
renderCount++;
} else {
renderCount = 1;
}

if (renderCount >= 25) {
throw new Error(
`Too many re-renders. This is limited to prevent an infinite loop ` +
`which may lock up your browser. The component causing this is: ${getDisplayName(
vnode
)}`
);
}

currentComponent = nextComponent;
};

options._hook = (comp, index, type) => {
Expand Down
32 changes: 32 additions & 0 deletions debug/test/browser/debug.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createElement, render, createRef, Component, Fragment } from 'preact';
import { useState } from 'preact/hooks';
import {
setupScratch,
teardown,
Expand Down Expand Up @@ -271,6 +272,37 @@ describe('debug', () => {
expect(console.error).to.not.be.called;
});

it('throws an error if a component rerenders too many times', () => {
let rerenderCount = 0;
function TestComponent({ loop = false }) {
const [count, setCount] = useState(0);
if (loop) {
setCount(count + 1);
}

if (count > 30) {
expect.fail(
'Repeated rerenders did not cause the expected error. This test is failing.'
);
}

rerenderCount += 1;
return <div />;
}

expect(() => {
render(
<Fragment>
<TestComponent />
<TestComponent loop />
</Fragment>,
scratch
);
}).to.throw(/Too many re-renders/);
// 1 for first TestComponent + 24 for second TestComponent
expect(rerenderCount).to.equal(25);
});

describe('duplicate keys', () => {
const List = props => <ul>{props.children}</ul>;
const ListItem = props => <li>{props.children}</li>;
Expand Down

0 comments on commit 50c3f3e

Please sign in to comment.