title: Closing Multiple React Components - one after another
body: <p>I read through a lot of "close react component on escape / outside click" threads and am able to close <strong>all</strong> opened react components at once. </p>
  
  <p>But: When 2 popups are opened, i want to first close the one "on top", then the one behind it, not <strong>both at the same time</strong>. Here is a pic of the application:</p>
  
  <p><a href="https://i.stack.imgur.com/JsP1B.png" rel="nofollow noreferrer">Screenshot Application with Popups to close</a></p>
  
  <p>My code for a custom hook to close the components:</p>
  
  <pre><code>import { useRef, useEffect } from 'react';
  
  export const useOutsideClick = (ref: any, callback: any, when: boolean) =&gt; {
    const savedCallback = useRef(callback);
  
    useEffect(() =&gt; {
      savedCallback.current = callback;
    });
  
    const handler = (e: any) =&gt; {
      // check if target event is within the ref
  
      if (ref.current &amp;&amp; !ref.current.contains(e.target)) {
        console.log('Handler handling states!');
        savedCallback.current();
      }
    };
  
    useEffect(() =&gt; {
      if (when) {
        document.addEventListener('click', handler);
        return () =&gt; document.removeEventListener('click', handler);
      }
    }, [when]);
  };
  </code></pre>
  
  <p>With the <code>useRef</code> i am creating a connection to a div that needs to be closed an call the <code>useOutsideClick()</code> function.</p>
  
  <p>Any ideas how i can achieve closing one component after another? 
  Thanks &amp; Greetings!</p>
  
  <p>EDIT: The thing is, i can also close just a single component. The problem is, that like this, the application doesnt know when i click on some other component, it just notices the click when i click on the space where no component is rendered.</p>