I have a React component that uses a useEffect
to open a popup window when the component is mount (the component is a screen).
useEffect(() => {
window.open(...);
}, []);
With strict mode this ends up opening two popups. I know I could use a ref but this seems to circumvent the reason why React strict mode runs the effects twice. What would be a correct way to handle this with React resumability in mind?
2
Answers
To prevent the useEffect from running twice in React strict mode and still achieve the desired behavior of opening a popup window only once when the component mounts, you can use a ref to keep track of whether the effect has already been triggered.
Here’s how you can do it:
you can add this hook to run it only once:
and use it: