Skip to content

Commit b3c7a5d

Browse files
authored
fix: mount devtools overlay only if react devtools are connected (#38784)
1 parent 7636e4c commit b3c7a5d

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

Libraries/ReactNative/AppContainer.js

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import {type EventSubscription} from '../vendor/emitter/EventEmitter';
1717
import {RootTagContext, createRootTag} from './RootTag';
1818
import * as React from 'react';
1919

20+
const reactDevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
21+
2022
type Props = $ReadOnly<{|
2123
children?: React.Node,
2224
fabric?: boolean,
@@ -45,9 +47,17 @@ class AppContainer extends React.Component<Props, State> {
4547
};
4648
_mainRef: ?React.ElementRef<typeof View>;
4749
_subscription: ?EventSubscription = null;
50+
_reactDevToolsAgentListener: ?() => void = null;
4851

4952
static getDerivedStateFromError: any = undefined;
5053

54+
mountReactDevToolsOverlays(): void {
55+
const DevtoolsOverlay = require('../Inspector/DevtoolsOverlay').default;
56+
const devtoolsOverlay = <DevtoolsOverlay inspectedView={this._mainRef} />;
57+
58+
this.setState({devtoolsOverlay});
59+
}
60+
5161
componentDidMount(): void {
5262
if (__DEV__) {
5363
if (!this.props.internal_excludeInspector) {
@@ -69,13 +79,21 @@ class AppContainer extends React.Component<Props, State> {
6979
this.setState({inspector});
7080
},
7181
);
72-
if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__ != null) {
73-
const DevtoolsOverlay =
74-
require('../Inspector/DevtoolsOverlay').default;
75-
const devtoolsOverlay = (
76-
<DevtoolsOverlay inspectedView={this._mainRef} />
82+
83+
if (reactDevToolsHook != null) {
84+
if (reactDevToolsHook.reactDevtoolsAgent) {
85+
// In case if this is not the first AppContainer rendered and React DevTools are already attached
86+
this.mountReactDevToolsOverlays();
87+
return;
88+
}
89+
90+
this._reactDevToolsAgentListener = () =>
91+
this.mountReactDevToolsOverlays();
92+
93+
reactDevToolsHook.on(
94+
'react-devtools',
95+
this._reactDevToolsAgentListener,
7796
);
78-
this.setState({devtoolsOverlay});
7997
}
8098
}
8199
}
@@ -85,6 +103,10 @@ class AppContainer extends React.Component<Props, State> {
85103
if (this._subscription != null) {
86104
this._subscription.remove();
87105
}
106+
107+
if (reactDevToolsHook != null && this._reactDevToolsAgentListener != null) {
108+
reactDevToolsHook.off('react-devtools', this._reactDevToolsAgentListener);
109+
}
88110
}
89111

90112
render(): React.Node {

0 commit comments

Comments
 (0)