title: Create an precise amount of ref after rerender
body: <p>I've come across a react hurdle.</p>
  <ol>
  <li>I'm trying to render a component that creates the amount of subcomponents I want.</li>
  <li>But those subcomponents need refs.</li>
  <li>And the amount of components that will be rendered may vary and so will the amount of refs needed.</li>
  <li>Also it is possible that the component may already have been rendered and may need to increase its amount of subcomponent those further increasing the amount of refs needed.</li>
  </ol>
  <p><strong>The problem</strong></p>
  <p>The problem is that I can not create those refs in the exact amount I want because.</p>
  <ol>
  <li>It happens after render.</li>
  <li>The order in which it happens does not allow for my refs to be created before a rerender.</li>
  </ol>
  <p><strong>What I've tried so far</strong></p>
  <p>In order to do so I have my index component with which on the pressing of the key c calls a function (an useImperativeHandle). This function either tries to change one state by storing all the info needed for the render of the subcomponents(like the refs).</p>
  <p>With this method I get the error that hooks can only be called inside component functions (the useRef in this case).</p>
  <pre><code>const newSoldiersAmount = (soldierInfos.numberOfSoldiers || 0) + nbAllies
    const newObjectRefs = [...new Array(newSoldiersAmount)].map((el) =&gt; useRef())
    const newRefs = [...new Array(newSoldiersAmount)].map((el) =&gt; useRef())
    let newSoldierInfo = {
      numberOfSoldiers: newSoldiersAmount,
      listOfAlive: [...new Array(newSoldiersAmount)].map((el) =&gt; true),
      objectRefs: newObjectRefs,
      refs: newRefs
    }
    setSoldierInfos({ ...newSoldierInfo })
  </code></pre>
  <p>I've tried useEffect which results in the same problem.</p>
  <p>I've also tried another approach where I just set the amount of subcomponents I want to render and creating the refs directly from this number but then I get the error React has detected a change in the order of Hooks called by ForwardRef.</p>
  <pre><code>const mycomponent = forwardRef((props,ref)=&gt;{
    let objectRefs = [...new Array(soldierInfos.numberOfSoldiers || 0)].map((el) =&gt; useRef())
    let refs = [...new Array(soldierInfos.numberOfSoldiers || 0)].map((el) =&gt; useRef())
  /*the rest of the code*/
  </code></pre>
  <p><strong>The code</strong></p>
  <p>I've put my code in this codeSandbox :
  <a href="https://codesandbox.io/embed/react-three-fiber-wildlife-nrbnq?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="nofollow noreferrer">the codesandbox where my code is</a></p>