title: Understanding React functional components that return mapped child components
body: <p>Today I spent quite a bit of time debugging an issue with state resetting itself in child components on every re-render. After eventually solving it I realized that I don't fully understand how React functional components and Array.map() work together, which is why I'm hoping that someone can shed some light on the issue I was having:</p>
  
  <p>Let's say I have an <code>ItemWrapper</code> component that returns (among other things) an <code>ItemListA</code> component. <code>ItemListA</code> maps over an array and returns a list of <code>Item</code> components. Each <code>Item</code> component has its own state that changes on certain actions.</p>
  
  <p>The way I did it at first:</p>
  
  <pre><code>const ItemWrapper = ({ items }) =&gt;  {
      const [someState, setSomeState] = useState(null);
      const someFunction = value =&gt; setSomeState(value);
  
      ...
  
      const ItemListA = () =&gt; items.map(item =&gt;
          &lt;Item
              key={item.id}
              item={item}
              callback={someFunction}
          /&gt;
      )
  
      ...
  
      return (
          &lt;div&gt;
              &lt;ItemListA /&gt;
          &lt;/div&gt;
      );
  };
  </code></pre>
  
  <p>The problem: whenever the <code>someFunction</code> callback was invoked in one of the <code>Item</code> children, this caused <code>ItemWrapper</code> to re-render and reset the state of all of the other <code>Item</code> children.</p>
  
  <p>Solved it by storing the item list in a local variable rather than a component:</p>
  
  <pre><code>const ItemWrapper = ({ items }) =&gt;  {
      const [someState, setSomeState] = useState(null);
      const someFunction = value =&gt; setSomeState(value);
  
      ...
  
      const itemListB = items.map(item =&gt;
          &lt;Item
              key={item.id}
              item={item}
              callback={someFunction}
          /&gt;
      );
  
      ...
  
      return (
          &lt;div&gt;
              {itemListB}
          &lt;/div&gt;
      );
  };
  </code></pre>
  
  <p>I don't feel like I fully understand what's going on here. My guess would be that storing the item list in a functional component somehow made it so that the <code>ItemListA</code> component and its children (with the exception of the one that triggered the callback - no idea why) were destroyed and then rebuilt whenever the <code>ItemWrapper</code> component was re-rendered, meaning that there was no trace left of their previous state. Is it because <code>ItemListA</code> is a function and every re-render creates a new reference?</p>