Description
React version:
- Works in React v17.1.0
- Doesn't work in React v18.0.0 & v18.1.0
Steps To Reproduce
Link to code example:
- Broken React 18: https://codesandbox.io/s/nifty-bash-366bs4?file=/src/App.js
- This version uses the latest
react@next react-dom@next
to verify that the latest (unreleased) version doesn't work either.
- This version uses the latest
- Working React 17: https://codesandbox.io/s/infallible-pine-n9vb4c?file=/src/App.js
The current behavior
If you open the React 18 CodeSandbox link from above, what you will notice when you hit the Open Dialog
button is that you will receive an event like Got event in <Dialog />!
I tried to minimize the reproduction, the idea is that we have a Dialog
component that receives an open
prop, based on this prop we know to show the Dialog
or not. However a Dialog
should also have "outside click" behaviour, to fake this I setup a window.addEventListener('click')
inside a useEffect to "capture" this behaviour. However when I click the Open Dialog
button this is what happens:
- Click
Open Dialog
- Set
open
state totrue
- Re-render component
- Pass
open={true}
to theDialog
component - In a useEffect, setup the
window.addEventListener('click')
if theopen
value is true - The callback of the event listener receives the
click
event from step 1.
Console logs after clicking once on the Open Dialog
button:
Open: false
*onClick*
Open: true
Got event in <Dialog />!
The expected behavior
If you open the React 17 CodeSandbox and repeat those steps from above, then you will see the expected behaviour where clicking on the Open Dialog
does not trigger the log from within the window.addEventListener('click')
it's only the second time that you click that button that it will log something because now the Dialog
is considered in an open
state.
Console logs after clicking once on the Open Dialog
button:
Open: false
*onClick*
Open: true
Is this a bug, a regression or am I doing something incorrect here? I'm confused how a window.addEventListener
can receive an event from a click that happened before the listener was even setup 🤔