From 4392e3821d4e3845a2ffc6104c32c13b3f521edf Mon Sep 17 00:00:00 2001 From: Brian Vaughn Date: Tue, 15 Jan 2019 13:49:39 -0800 Subject: [PATCH] useDebugValue should throw if used in a class component (#14601) --- .../react-reconciler/src/ReactFiberHooks.js | 3 +++ .../src/__tests__/ReactHooks-test.internal.js | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/packages/react-reconciler/src/ReactFiberHooks.js b/packages/react-reconciler/src/ReactFiberHooks.js index 2f8d9a24a5658..fa572a882ff46 100644 --- a/packages/react-reconciler/src/ReactFiberHooks.js +++ b/packages/react-reconciler/src/ReactFiberHooks.js @@ -592,6 +592,9 @@ export function useDebugValue( value: any, formatterFn: ?(value: any) => any, ): void { + // This will trigger a warning if the hook is used in a non-Function component. + resolveCurrentlyRenderingFiber(); + // This hook is normally a no-op. // The react-debug-hooks package injects its own implementation // so that e.g. DevTools can display custom hook values. diff --git a/packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js b/packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js index 709d819d6713e..7b442ebf77eda 100644 --- a/packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js +++ b/packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js @@ -31,6 +31,23 @@ describe('ReactHooks', () => { ReactDOMServer = require('react-dom/server'); }); + if (__DEV__) { + // useDebugValue is a DEV-only hook + it('useDebugValue throws when used in a class component', () => { + class Example extends React.Component { + render() { + React.useDebugValue('abc'); + return null; + } + } + expect(() => { + ReactTestRenderer.create(); + }).toThrow( + 'Hooks can only be called inside the body of a function component.', + ); + }); + } + it('warns about variable number of dependencies', () => { const {useLayoutEffect} = React; function App(props) {