Skip to content

Commit 4392e38

Browse files
authored
useDebugValue should throw if used in a class component (#14601)
1 parent 153a0b5 commit 4392e38

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

packages/react-reconciler/src/ReactFiberHooks.js

+3
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,9 @@ export function useDebugValue(
592592
value: any,
593593
formatterFn: ?(value: any) => any,
594594
): void {
595+
// This will trigger a warning if the hook is used in a non-Function component.
596+
resolveCurrentlyRenderingFiber();
597+
595598
// This hook is normally a no-op.
596599
// The react-debug-hooks package injects its own implementation
597600
// so that e.g. DevTools can display custom hook values.

packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js

+17
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@ describe('ReactHooks', () => {
3131
ReactDOMServer = require('react-dom/server');
3232
});
3333

34+
if (__DEV__) {
35+
// useDebugValue is a DEV-only hook
36+
it('useDebugValue throws when used in a class component', () => {
37+
class Example extends React.Component {
38+
render() {
39+
React.useDebugValue('abc');
40+
return null;
41+
}
42+
}
43+
expect(() => {
44+
ReactTestRenderer.create(<Example />);
45+
}).toThrow(
46+
'Hooks can only be called inside the body of a function component.',
47+
);
48+
});
49+
}
50+
3451
it('warns about variable number of dependencies', () => {
3552
const {useLayoutEffect} = React;
3653
function App(props) {

0 commit comments

Comments
 (0)