reactjsreact-hooks

Popup using useState stopped working in React 18


I made a popup using useState which worked in React 17 but stopped in React 18 without any errors being displayed.

When I set the isVisible state to be true initially the Popup gets displayed but setting it to using the button does not work.

I'm wondering why this is the case and how I can migrate it to React 18 since I need it for other dependencies in my project.

{isVisible && (
  <Popup
    visible={isVisible}
    toggle={() => {
      setLightboxVisible(false);
      document.body.classList.toggle("body-noscroll-class");
    }}
  >
    Lorem Ipsum dolor sit amet.
  </Popup>
)}

<button 
  onClick={() => {
    setLightboxVisible(true);
  }}>
Show Popup
</button>

Here is a Codesandbox which shows the behavior.


Solution

  • Fixed by changing click to mousedown in the useOuterClick hook, as suggested by @Miłosz

    https://codesandbox.io/s/relaxed-cdn-vjih7v?file=/src/hooks.js