Skip to content

Commit

Permalink
feat: debug throw on too many rerenders (#4349)
Browse files Browse the repository at this point in the history
* [Compat] Throw an error for too many repeated function component rerenders

* refactor: Move limiter to debug

* revert: Unrelated changes

---------

Co-authored-by: Andre Wiggins <andrewiggins@live.com>
  • Loading branch information
rschristian and andrewiggins committed Apr 26, 2024
1 parent aa95aa9 commit 613cacc
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
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
@@ -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 613cacc

Please sign in to comment.