Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid calling `useState` in a map method?

I have a snippet within a React component similar to this:

<div>
  {items.map((item) => {
    const [isExpanded, setIsExpanded] = useState(false)

    return (
      // ...     
    )
  })}
</div>

I am calling useState in a map method, but I read in the documentation that hooks must be top level. I am wondering how could I refactor this code to avoid doing it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

option 1

In your case i would suggest creating a new component for the item.

<div>
  { items.map((item) => <Item key={} />) }
</div>

...
const Item = () => {
    const [isExpanded, setIsExpanded] = useState(false)

    return (
      // ...     
    )}
}

option 2


const [expandedIds, setExpandedIds] = useState([])
...
<div>
  {items.map((item) => {
    const expanded = checkIsExpended(item)
    return (
      // ...    
    )
  })}
</div>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading