Home > other >  How to avoid calling `useState` in a map method?
How to avoid calling `useState` in a map method?

Time:12-16

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?

CodePudding user response:

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>

  • Related