1 | initial version |
You can use the useEffect
hook to check whether the component has already mounted and then use window.open()
to open a new tab only if the component is mounted for the first time. Here's an example:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
const isOpened = localStorage.getItem('isOpened');
if (!isOpened) {
window.open('https://www.example.com', '_blank');
localStorage.setItem('isOpened', true);
}
}, []);
return <div>Hello world!</div>;
}
export default MyComponent;
In this example, we're using localStorage
to store a flag (isOpened
) that indicates whether the new tab has been opened before. By default, isOpened
is null
, so on the first mount of the component, the new tab will be opened and isOpened
will be set to true
. On subsequent mounts, isOpened
will have a value of true
, so the new tab won't be opened again.