If a component is rendered. I want to open a new tab. (window.open(url, "_blank")?.focus();
)
But (during development) this tab is opened twice because of the React.StrictMode.
How can I prevent this from being called multiple times without disabling the StrictMode?
My Attempts:
function MyComp() {
useMemo(() => window.open(url, "_blank")?.focus(), []);
return <div>...</div>;
}
(doesn’t work (called twice))
function MyComp() {
useEffect(() => {
const id = setTimeout(() => window.open(url, "_blank")?.focus(), 10);
return () => clearTimeout(id);
});
return <div>...</div>;
}
(works, but seems not like a good solution)
2
Answers
You can create this custom
useEffectOnce
hook in a separate file that will only execute code once, even duringStrictMode
:now instead of importing
useEffect
from React, importuseEffectOnce
from the directory you saved the hook in and do:You simply need to keep a track of whether you have already opened the new tab.