rmariuzzo / react-new-window

🔲 Pop new windows in React, using `window.open`.

Home Page:https://rmariuzzo.github.io/react-new-window/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PSA: React 18 StrictMode problematic for react-new-window

RobRendell opened this issue · comments

This is for the benefit of anyone else trying to use this package in React 18.

The React devs have made StrictMode deliberately unmount and remount newly mounted components, to try to force developers to make their components more resilient: reactwg/react-18#19

When StrictMode is enabled, React intentionally double-invokes effects (mount -> unmount -> mount) for newly mounted components. Like other strict mode behaviors, React will only do this for development builds.

This was a problem for my usage of react-new-window. Since an actual OS-controlled separate window can be unilaterally closed by the user, I use the onUnload callback to detect the window has been closed, and reset the internal state which says the window is open. However, since that state is what causes the NewWindow component to be rendered in the first place, the forced unmount was clearing the flag saying that the user wanted the window open, so it would stop being rendered. The forced "mount -> unmount -> mount" was equivalent to the user immediately hitting the [X] button to close the window.

You can set the closeOnUnmount flag to false to avoid the window being closed (and onUnload being called) when the component is force-unmounted, but then your application loses the ability to close the window programmatically by stopping rendering it.

So, frankly this is a bit of a pain in the butt.

The good news is that this behaviour will only happen in development builds, and only if you wrap your application in <StrictMode> tags. The window should render properly without the spurious force-unmount in production code, and if you want to keep using StrictMode to catch other problems while doing your development, you can temporarily remove the StrictMode tags when you're doing dev work that involves the actual NewWindow.

Thank you for all the details, it helps me a lot. For now, I think this issue has been addressed by: #134

If you consider more specific improvements can be done, please let me know.