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)
>Solution :
You simply need to keep a track of whether you have already opened the new tab.
function MyComp() {
const openedNewTabRef = useRef(false);
useEffect(() => {
if (!openedNewTabRef?.current) {
window.open(url, "_blank")?.focus();
openedNewTabRef.current = true;
}
}, []);
return <div>...</div>;
}