Skip to content

Commit

Permalink
ReactDebugHooks useContext() advances hooks list in DEV mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Vaughn committed Feb 24, 2019
1 parent ba708fa commit e777462
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/react-debug-tools/src/ReactDebugHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ function useContext<T>(
context: ReactContext<T>,
observedBits: void | number | boolean,
): T {
if (__DEV__) {
// ReactFiberHooks only adds context to the hooks list in DEV.
nextHook();
}
hookLog.push({
primitive: 'Context',
stackError: new Error(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,4 +427,31 @@ describe('ReactHooksInspectionIntegration', () => {
expect(setterCalls[0]).not.toBe(initial);
expect(setterCalls[1]).toBe(initial);
});

// This test case is based on an open source bug report:
// facebookincubator/redux-react-hook/issues/34#issuecomment-466693787
it('should properly advance the current hook for useContext', () => {
const MyContext = React.createContext(123);

let hasInitializedState = false;
const initializeStateOnce = () => {
if (hasInitializedState) {
throw Error(
'State initialization function should only be called once.',
);
}
hasInitializedState = true;
return {foo: 'abc'};
};

function Foo(props) {
React.useContext(MyContext);
const [data] = React.useState(initializeStateOnce);
return <div>foo: {data.foo}</div>;
}

const renderer = ReactTestRenderer.create(<Foo />);
const childFiber = renderer.root._currentFiber();
ReactDebugTools.inspectHooksOfFiber(childFiber);
});
});
2 changes: 2 additions & 0 deletions packages/react-reconciler/src/ReactFiberHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ function mountContext<T>(
observedBits: void | number | boolean,
): T {
if (__DEV__) {
// If this DEV conditional is ever removed, update ReactDebugHooks useContext too.
mountWorkInProgressHook();
}
return readContext(context, observedBits);
Expand All @@ -535,6 +536,7 @@ function updateContext<T>(
observedBits: void | number | boolean,
): T {
if (__DEV__) {
// If this DEV conditional is ever removed, update ReactDebugHooks useContext too.
updateWorkInProgressHook();
}
return readContext(context, observedBits);
Expand Down

0 comments on commit e777462

Please sign in to comment.