title: Is my entire React component re-rendering unnecessarily when the state changes?
body: <p>I am trying to create an accordion component using React, but the animation is not working. </p>
  
  <p>The basic idea is, I believe, pretty standard, I am giving each item body a <code>max-height</code> of <code>0</code> which is affected by adding a <code>show</code> class to an element. I am able to select and show the item I want, but the animation to slide in/out is not working.</p>
  
  <p>With the Chrome dev tools open, when I click on one of the items I can see that the whole "accordion" element is flashing, which leads me to believe that the whole element is being re-rendered. But I am unsure why this would be the case. </p>
  
  <p>Here is the relevant <code>Accordion</code> component:</p>
  
  <pre><code>import React, { useState } from "react";
  
  const Accordion = ({ items }) =&gt; {
    const [selectedItem, setSelectedItem] = useState(0);
  
    const AccordionItem = ({ item, index }) =&gt; {
      const isOpen = index === selectedItem;
      return (
        &lt;div className="accordion-item"&gt;
          &lt;div
            onClick={() =&gt; {
              setSelectedItem(index);
            }}
            className="accordion-header"
          &gt;
            &lt;div&gt;{item.heading}&lt;/div&gt;
          &lt;/div&gt;
          &lt;div className={`accordion-body ${isOpen ? "show" : ""}`}&gt;
            &lt;div className="accordion-content"&gt;{item.body}&lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      );
    };
  
    return (
      &lt;div className="accordion"&gt;
        {items.map((item, i) =&gt; {
          return &lt;AccordionItem key={i} item={item} index={i} /&gt;;
        })}
      &lt;/div&gt;
    );
  };
  
  export default Accordion;
  </code></pre>
  
  <p>And here is a codepen illustrating the problem:</p>
  
  <p><a href="https://codesandbox.io/s/heuristic-heyrovsky-xgcbe" rel="nofollow noreferrer">https://codesandbox.io/s/heuristic-heyrovsky-xgcbe</a></p>