skip to Main Content

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


  1. 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:

    import React, { useEffect, useRef } from 'react';
    
    const MyComponent = () => {
      const popupOpenedRef = useRef(false);
    
      useEffect(() => {
     
        if (!popupOpenedRef.current) {
          window.open(...);
          popupOpenedRef.current = true;
        }
      }, []);
    
      return (
        // Your component JSX
      );
    };
    
    export default MyComponent;
    
    Login or Signup to reply.
  2. you can add this hook to run it only once:

    import { DependencyList, EffectCallback, useEffect, useRef } from "react";
    
    const useEffectAfterMount = (cb: EffectCallback, dependencies: DependencyList | undefined) => {
      const mounted = useRef(false);
    
      useEffect(() => {
        if (mounted.current) {
          return cb();
        }
        mounted.current = true;
      }, dependencies);
    };
    
    export default useEffectAfterMount;
    

    and use it:

      useEffectAfterMount(() => {
       window.open(...);
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search