From 01a1ac8ffbf315d9de39139d53c785281e2aa933 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Sat, 3 Feb 2024 19:39:02 +0000 Subject: [PATCH] Re-add the warning for useContext(Context.Consumer) --- .../src/__tests__/ReactNewContext-test.js | 12 ++++++++++++ packages/react/src/ReactHooks.js | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/packages/react-reconciler/src/__tests__/ReactNewContext-test.js b/packages/react-reconciler/src/__tests__/ReactNewContext-test.js index 3d7636c924829..8c6476345beeb 100644 --- a/packages/react-reconciler/src/__tests__/ReactNewContext-test.js +++ b/packages/react-reconciler/src/__tests__/ReactNewContext-test.js @@ -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(); + 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 diff --git a/packages/react/src/ReactHooks.js b/packages/react/src/ReactHooks.js index cea86dc72288a..3d67608c87d75 100644 --- a/packages/react/src/ReactHooks.js +++ b/packages/react/src/ReactHooks.js @@ -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'; @@ -71,6 +72,14 @@ export function getCacheForType(resourceType: () => T): T { export function useContext(Context: ReactContext): 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); }