Skip to content

Instantly share code, notes, and snippets.

@nhusher
Last active September 30, 2022 15:42
Show Gist options
  • Save nhusher/33981014bb69318ead012c11a73eff52 to your computer and use it in GitHub Desktop.
Save nhusher/33981014bb69318ead012c11a73eff52 to your computer and use it in GitHub Desktop.
Bizarre React Devtools problem

Usage:

git clone git@gist.github.com:33981014bb69318ead012c11a73eff52.git react-issue-repro
npx static-server

Visit the URL provided by static-server.

  1. Have React devtools installed
  2. Visit the URL indicated by static-server
  3. Click both increment buttons, ensuring that they work
  4. Open the developer tools
  5. Navigate to the DevTools Component tree and highlight <App />
  6. Click both the increment buttons
  7. Observe that the normal in-React increment button works
  8. Observe that the "increment (outside react)" button no longer works

Verification of the issue:

  1. Open an incognito window
  2. Visit the URL indicated by static-server
  3. Click the two buttons and verify that both work
  4. Open the developer tools (no React Devtools available)
  5. Verify the two buttons continue to work
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="react-app"></div>
<div id="some-outside-app">
</div>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="./script.js"></script>
</body>
</html>
const {
createElement: E,
useCallback,
useDebugValue,
useState
} = React;
const {
createRoot
} = ReactDOM
function useCounter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((c) => c + 1);
}, []);
useDebugValue({ count });
return [
count,
increment
];
}
function App() {
const [count, increment] = useCounter();
window.__REACT__increment = increment;
console.log("RENDER!");
return (
E('div', {},
E('h1', {}, count),
E('button', { type: 'button', onClick: increment },
'increment'))
);
}
const reactRoot = createRoot(document.getElementById('react-app'))
reactRoot.render(E(App, {}))
const outsideRoot = document.getElementById("some-outside-app");
const el = document.createElement("button");
el.innerHTML = "increment (outside react)";
el.onclick = () => {
// This doesn't work reliably when devtools are viewing the React tree:
if (window.__REACT__increment) window.__REACT__increment();
else console.error("No react increment function available!");
};
outsideRoot.appendChild(el);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment