Skip to content

Commit e777462

Browse files
author
Brian Vaughn
committed
ReactDebugHooks useContext() advances hooks list in DEV mode
1 parent ba708fa commit e777462

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

packages/react-debug-tools/src/ReactDebugHooks.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,10 @@ function useContext<T>(
9393
context: ReactContext<T>,
9494
observedBits: void | number | boolean,
9595
): T {
96+
if (__DEV__) {
97+
// ReactFiberHooks only adds context to the hooks list in DEV.
98+
nextHook();
99+
}
96100
hookLog.push({
97101
primitive: 'Context',
98102
stackError: new Error(),

packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,4 +427,31 @@ describe('ReactHooksInspectionIntegration', () => {
427427
expect(setterCalls[0]).not.toBe(initial);
428428
expect(setterCalls[1]).toBe(initial);
429429
});
430+
431+
// This test case is based on an open source bug report:
432+
// facebookincubator/redux-react-hook/issues/34#issuecomment-466693787
433+
it('should properly advance the current hook for useContext', () => {
434+
const MyContext = React.createContext(123);
435+
436+
let hasInitializedState = false;
437+
const initializeStateOnce = () => {
438+
if (hasInitializedState) {
439+
throw Error(
440+
'State initialization function should only be called once.',
441+
);
442+
}
443+
hasInitializedState = true;
444+
return {foo: 'abc'};
445+
};
446+
447+
function Foo(props) {
448+
React.useContext(MyContext);
449+
const [data] = React.useState(initializeStateOnce);
450+
return <div>foo: {data.foo}</div>;
451+
}
452+
453+
const renderer = ReactTestRenderer.create(<Foo />);
454+
const childFiber = renderer.root._currentFiber();
455+
ReactDebugTools.inspectHooksOfFiber(childFiber);
456+
});
430457
});

packages/react-reconciler/src/ReactFiberHooks.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,7 @@ function mountContext<T>(
525525
observedBits: void | number | boolean,
526526
): T {
527527
if (__DEV__) {
528+
// If this DEV conditional is ever removed, update ReactDebugHooks useContext too.
528529
mountWorkInProgressHook();
529530
}
530531
return readContext(context, observedBits);
@@ -535,6 +536,7 @@ function updateContext<T>(
535536
observedBits: void | number | boolean,
536537
): T {
537538
if (__DEV__) {
539+
// If this DEV conditional is ever removed, update ReactDebugHooks useContext too.
538540
updateWorkInProgressHook();
539541
}
540542
return readContext(context, observedBits);

0 commit comments

Comments
 (0)