Skip to content

Commit

Permalink
Re-add the warning for useContext(Context.Consumer)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Feb 3, 2024
1 parent e0d0703 commit 01a1ac8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/react-reconciler/src/__tests__/ReactNewContext-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,18 @@ describe('ReactNewContext', () => {
);
});

it('warns when passed a consumer', async () => {
const Context = React.createContext(0);
function Foo() {
return useContext(Context.Consumer);
}
ReactNoop.render(<Foo />);
await expect(async () => await waitForAll([])).toErrorDev(
'Calling useContext(Context.Consumer) is not supported and will cause bugs. ' +
'Did you mean to call useContext(Context) instead?',
);
});

// Context consumer bails out on propagating "deep" updates when `value` hasn't changed.
// However, it doesn't bail out from rendering if the component above it re-rendered anyway.
// If we bailed out on referential equality, it would be confusing that you
Expand Down
9 changes: 9 additions & 0 deletions packages/react/src/ReactHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
StartTransitionOptions,
Usable,
} from 'shared/ReactTypes';
import {REACT_CONSUMER_TYPE} from 'shared/ReactSymbols';

import ReactCurrentDispatcher from './ReactCurrentDispatcher';
import ReactCurrentCache from './ReactCurrentCache';
Expand Down Expand Up @@ -71,6 +72,14 @@ export function getCacheForType<T>(resourceType: () => T): T {

export function useContext<T>(Context: ReactContext<T>): T {
const dispatcher = resolveDispatcher();
if (__DEV__) {
if (Context.$$typeof === REACT_CONSUMER_TYPE) {
console.error(
'Calling useContext(Context.Consumer) is not supported and will cause bugs. ' +
'Did you mean to call useContext(Context) instead?',
);
}
}
return dispatcher.useContext(Context);
}

Expand Down

0 comments on commit 01a1ac8

Please sign in to comment.