Skip to content

Commit

Permalink
fix[AppContainer]: mount react devtools overlay only when devtools ar…
Browse files Browse the repository at this point in the history
…e attached (#38785)

resolved: #38727
Fixes #38024.
  • Loading branch information
hoxyq committed Aug 7, 2023
1 parent 79c4ec1 commit 03187b6
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions packages/react-native/Libraries/ReactNative/AppContainer.js
Expand Up @@ -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,
Expand Down Expand Up @@ -47,9 +49,21 @@ class AppContainer extends React.Component<Props, State> {
};
_mainRef: ?React.ElementRef<typeof View>;
_subscription: ?EventSubscription = null;
_reactDevToolsAgentListener: ?() => void = null;

static getDerivedStateFromError: any = undefined;

mountReactDevToolsOverlays(): void {
const DevtoolsOverlay = require('../Inspector/DevtoolsOverlay').default;
const devtoolsOverlay = <DevtoolsOverlay inspectedView={this._mainRef} />;

const TraceUpdateOverlay =
require('../Components/TraceUpdateOverlay/TraceUpdateOverlay').default;
const traceUpdateOverlay = <TraceUpdateOverlay />;

this.setState({devtoolsOverlay, traceUpdateOverlay});
}

componentDidMount(): void {
if (__DEV__) {
if (!this.props.internal_excludeInspector) {
Expand All @@ -71,16 +85,21 @@ class AppContainer extends React.Component<Props, State> {
this.setState({inspector});
},
);
if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__ != null) {
const DevtoolsOverlay =
require('../Inspector/DevtoolsOverlay').default;
const devtoolsOverlay = (
<DevtoolsOverlay inspectedView={this._mainRef} />

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,
);
const TraceUpdateOverlay =
require('../Components/TraceUpdateOverlay/TraceUpdateOverlay').default;
const traceUpdateOverlay = <TraceUpdateOverlay />;
this.setState({devtoolsOverlay, traceUpdateOverlay});
}
}
}
Expand All @@ -90,6 +109,10 @@ class AppContainer extends React.Component<Props, State> {
if (this._subscription != null) {
this._subscription.remove();
}

if (reactDevToolsHook != null && this._reactDevToolsAgentListener != null) {
reactDevToolsHook.off('react-devtools', this._reactDevToolsAgentListener);
}
}

render(): React.Node {
Expand Down

0 comments on commit 03187b6

Please sign in to comment.