diff --git a/Libraries/ReactNative/AppContainer.js b/Libraries/ReactNative/AppContainer.js index cf3f1d0274e8e0..347bda2a2b4109 100644 --- a/Libraries/ReactNative/AppContainer.js +++ b/Libraries/ReactNative/AppContainer.js @@ -17,6 +17,8 @@ import {type EventSubscription} from '../vendor/emitter/EventEmitter'; import {RootTagContext, createRootTag} from './RootTag'; import * as React from 'react'; +const reactDevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; + type Props = $ReadOnly<{| children?: React.Node, fabric?: boolean, @@ -45,9 +47,17 @@ class AppContainer extends React.Component { }; _mainRef: ?React.ElementRef; _subscription: ?EventSubscription = null; + _reactDevToolsAgentListener: ?() => void = null; static getDerivedStateFromError: any = undefined; + mountReactDevToolsOverlays(): void { + const DevtoolsOverlay = require('../Inspector/DevtoolsOverlay').default; + const devtoolsOverlay = ; + + this.setState({devtoolsOverlay}); + } + componentDidMount(): void { if (__DEV__) { if (!this.props.internal_excludeInspector) { @@ -69,13 +79,21 @@ class AppContainer extends React.Component { this.setState({inspector}); }, ); - if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__ != null) { - const DevtoolsOverlay = - require('../Inspector/DevtoolsOverlay').default; - const devtoolsOverlay = ( - + + if (reactDevToolsHook != null) { + if (reactDevToolsHook.reactDevtoolsAgent) { + // In case if this is not the first AppContainer rendered and React DevTools are already attached + this.mountReactDevToolsOverlays(); + return; + } + + this._reactDevToolsAgentListener = () => + this.mountReactDevToolsOverlays(); + + reactDevToolsHook.on( + 'react-devtools', + this._reactDevToolsAgentListener, ); - this.setState({devtoolsOverlay}); } } } @@ -85,6 +103,10 @@ class AppContainer extends React.Component { if (this._subscription != null) { this._subscription.remove(); } + + if (reactDevToolsHook != null && this._reactDevToolsAgentListener != null) { + reactDevToolsHook.off('react-devtools', this._reactDevToolsAgentListener); + } } render(): React.Node {