title: How can I call React useRef conditionally in a Portal wrapper and have better code?
body: <p>I am attempting to make a simple Portal wrapper that does the following.</p>
  <ol>
  <li>Can render multiple portals on the same view</li>
  <li>Can render multiple portals by targeting parent ids. This cannot be done by passing a ref into the component since the container may live anywhere.</li>
  <li>Can render multiple portal without any parent targets</li>
  </ol>
  <p>This is what I came up with this morning. The code works exactly how I want it to work. It creates portals with or without a parent target and cleans up completely. However React says not to call hooks from conditions, which you can see I have done here by calling useRef within a ternary. I have not seen any warnings or errors but I am also developing this code in a custom setup with Webpack and Typescript. I have not pushed this code to NPM to see what happens when I import the library into a project. My guess is there's going to be issues. Is there a better way to do this?</p>
  <p>Thanks in advance.</p>
  <p><em><strong>Calling Component:</strong></em></p>
  <pre><code>&lt;div&gt;
    {open1 &amp;&amp; (
      &lt;Portal parentId=&quot;panel-1&quot;&gt;
        &lt;Panel title=&quot;Poopster&quot; onClose={handleClose1}&gt;
          &lt;div&gt;Panel&lt;/div&gt;
        &lt;/Panel&gt;
      &lt;/Portal&gt;
    )}
    {open2 &amp;&amp; (
      &lt;Portal&gt;
        &lt;Panel onClose={handleClose2}&gt;
          &lt;div&gt;Panel&lt;/div&gt;
        &lt;/Panel&gt;
      &lt;/Portal&gt;
    )}
  &lt;div&gt;
  </code></pre>
  <p><em><strong>Portal Component</strong></em></p>
  <pre><code>import * as React from 'react';
  import { createPortal } from 'react-dom';
  
  export interface PortalProps {
    children: React.ReactElement;
    parentId?: string;
  }
  
  export const Portal = ({
    children,
    parentId
  }: PortalProps): React.ReactElement =&gt; {
  
    let ref = !parentId ?
      React.useRef(document.createElement('div')) :
      React.useRef(document.getElementById(parentId));
  
    React.useEffect((): VoidFunction =&gt; {
      return (): void =&gt; {
        if (!parentId &amp;&amp; ref.current) {
          document.body.removeChild(ref.current);
        }
  
        ref = null;
      };
    }, []);
  
    React.useEffect(() =&gt; {
      if (!parentId &amp;&amp; ref.current) {
        document.body.appendChild(ref.current);
      }
    }, [ref, parentId]);
  
    return createPortal(children, ref.current);
  };
  
  export default Portal;
  </code></pre>