@samitouri / QOS-React-2 / commits / 4387d752da

Allow more hooks to be added when replaying mount

Currently, if you call setState in render, you must render the exact same hooks as during the first render pass. I'm about to add a behavior where if something suspends, we can reuse the hooks from the previous attempt. That means during initial render, if something suspends, we should be able to reuse the hooks that were already created and continue adding more after that. This will error in the current implementation because of the expectation that every render produces the same list of hooks. In this commit, I've changed the logic to allow more hooks to be added when replaying. But only during a mount — if there's already a current fiber, then the logic is unchanged, because we shouldn't add any additional hooks that aren't in the current fiber's list. Mounts are special because there's no current fiber to compare to. I haven't change any other behavior yet. The reason I've put this into its own step is there are a couple tests that intentionally break the Hook rule, to assert that React errors in these cases, and those happen to be coupled to the behavior. This is undefined behavior that is always accompanied by a warning and/or error. So the change should be safe.

Andrew Clark committed Nov 2, 2022 at 22:50 UTC 4387d752dadada921938f9ea171d065b44a769c1
4 files changed +65 -23
packages/react-dom/src/__tests__/ReactDOMServerIntegrationHooks-test.js
+26 -20
@@ -430,26 +430,6 @@ describe('ReactDOMServerHooks', () => {
430 expect(domNode.textContent).toEqual('hi');
431 });
432
433 - itThrowsWhenRendering(
434 - 'with a warning for useRef inside useReducer',
435 - async render => {
436 - function App() {
437 - const [value, dispatch] = useReducer((state, action) => {
438 - useRef(0);
439 - return state + 1;
440 - }, 0);
441 - if (value === 0) {
442 - dispatch();
443 - }
444 - return value;
445 - }
446 -
447 - const domNode = await render(<App />, 1);
448 - expect(domNode.textContent).toEqual('1');
449 - },
450 - 'Rendered more hooks than during the previous render',
451 - );
452 -
433 itRenders('with a warning for useRef inside useState', async render => {
434 function App() {
435 const [value] = useState(() => {
@@ -686,6 +666,32 @@ describe('ReactDOMServerHooks', () => {
666 );
667 });
668
669 + describe('invalid hooks', () => {
670 + it('warns when calling useRef inside useReducer', async () => {
671 + function App() {
672 + const [value, dispatch] = useReducer((state, action) => {
673 + useRef(0);
674 + return state + 1;
675 + }, 0);
676 + if (value === 0) {
677 + dispatch();
678 + }
679 + return value;
680 + }
681 +
682 + let error;
683 + try {
684 + await serverRender(<App />);
685 + } catch (x) {
686 + error = x;
687 + }
688 + expect(error).not.toBe(undefined);
689 + expect(error.message).toContain(
690 + 'Rendered more hooks than during the previous render',
691 + );
692 + });
693 + });
694 +
695 itRenders(
696 'can use the same context multiple times in the same function',
697 async render => {
packages/react-reconciler/src/ReactFiberHooks.new.js
+18 -1
@@ -839,7 +839,24 @@ function updateWorkInProgressHook(): Hook {
839 // Clone from the current hook.
840
841 if (nextCurrentHook === null) {
842 - throw new Error('Rendered more hooks than during the previous render.');
842 + const currentFiber = currentlyRenderingFiber.alternate;
843 + if (currentFiber === null) {
844 + // This is the initial render. This branch is reached when the component
845 + // suspends, resumes, then renders an additional hook.
846 + const newHook: Hook = {
847 + memoizedState: null,
848 +
849 + baseState: null,
850 + baseQueue: null,
851 + queue: null,
852 +
853 + next: null,
854 + };
855 + nextCurrentHook = newHook;
856 + } else {
857 + // This is an update. We should always have a current hook.
858 + throw new Error('Rendered more hooks than during the previous render.');
859 + }
860 }
861
862 currentHook = nextCurrentHook;
packages/react-reconciler/src/ReactFiberHooks.old.js
+18 -1
@@ -839,7 +839,24 @@ function updateWorkInProgressHook(): Hook {
839 // Clone from the current hook.
840
841 if (nextCurrentHook === null) {
842 - throw new Error('Rendered more hooks than during the previous render.');
842 + const currentFiber = currentlyRenderingFiber.alternate;
843 + if (currentFiber === null) {
844 + // This is the initial render. This branch is reached when the component
845 + // suspends, resumes, then renders an additional hook.
846 + const newHook: Hook = {
847 + memoizedState: null,
848 +
849 + baseState: null,
850 + baseQueue: null,
851 + queue: null,
852 +
853 + next: null,
854 + };
855 + nextCurrentHook = newHook;
856 + } else {
857 + // This is an update. We should always have a current hook.
858 + throw new Error('Rendered more hooks than during the previous render.');
859 + }
860 }
861
862 currentHook = nextCurrentHook;
packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js
+3 -1
@@ -1071,7 +1071,9 @@ describe('ReactHooks', () => {
1071 expect(() => {
1072 expect(() => {
1073 ReactTestRenderer.create(<App />);
1074 - }).toThrow('Rendered more hooks than during the previous render.');
1074 + }).toThrow(
1075 + 'Should have a queue. This is likely a bug in React. Please file an issue.',
1076 + );
1077 }).toErrorDev([
1078 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks',
1079 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks',