Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[compiler runtime] repro: infinite render with useMemoCache + render phase updates #30849

Merged
merged 1 commit into from
Sep 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions packages/react-reconciler/src/__tests__/useMemoCache-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ let ReactNoop;
let Scheduler;
let act;
let assertLog;
let useMemo;
let useState;
let useMemoCache;
let waitForThrow;
let MemoCacheSentinel;
let ErrorBoundary;

Expand All @@ -27,8 +29,10 @@ describe('useMemoCache()', () => {
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
assertLog = require('internal-test-utils').assertLog;
useMemo = React.useMemo;
useMemoCache = require('react/compiler-runtime').c;
useState = React.useState;
waitForThrow = require('internal-test-utils').waitForThrow;
MemoCacheSentinel = Symbol.for('react.memo_cache_sentinel');

class _ErrorBoundary extends React.Component {
Expand Down Expand Up @@ -621,4 +625,59 @@ describe('useMemoCache()', () => {
</>,
);
});

// @gate enableUseMemoCacheHook
it('(repro) infinite renders when used with setState during render', async () => {
// Output of react compiler on `useUserMemo`
function useCompilerMemo(value) {
let arr;
const $ = useMemoCache(2);
if ($[0] !== value) {
arr = [value];
$[0] = value;
$[1] = arr;
} else {
arr = $[1];
}
return arr;
}

// Baseline / source code
function useUserMemo(value) {
return useMemo(() => [value], [value]);
}

function makeComponent(hook) {
return function Component({value}) {
const state = hook(value);
const [prevState, setPrevState] = useState(null);
if (state !== prevState) {
setPrevState(state);
}
return <div>{state.join(',')}</div>;
};
}

/**
* Test case: note that the initial render never completes
*/
let root = ReactNoop.createRoot();
const IncorrectInfiniteComponent = makeComponent(useCompilerMemo);
root.render(<IncorrectInfiniteComponent value={2} />);
await waitForThrow(
'Too many re-renders. React limits the number of renders to prevent ' +
'an infinite loop.',
);

/**
* Baseline test: initial render is expected to complete after a retry
* (triggered by the setState)
*/
root = ReactNoop.createRoot();
const CorrectComponent = makeComponent(useUserMemo);
await act(() => {
root.render(<CorrectComponent value={2} />);
});
expect(root).toMatchRenderedOutput(<div>2</div>);
});
});
Loading