0

I have an object in a useState as this:

const [sidebarItems, setSidebarItems] = useState([
     {
         id: 1,
         name: 'داشبورد',
         icon: <Item1 />,
         active: true
     }, ...];

I use the find method to get an object in the state and change it like this:

const handleToggle = (id) => {

     const activeMainItem = sidebarItems.find(i => i.active === true);
     activeMainItem.active = false;

}

I thought I should use setSidebarItems to change the array in the state but my code works well. Can you please explain to why this happens and doesn't need any setState?

clinton3141
  • 4,751
  • 3
  • 33
  • 46
Ali Bahaari
  • 421
  • 2
  • 8

1 Answers1

0

You can change the value of Array or Object, but you can not access the modified variable immediately inside your component it can not re-render your components because this is happening just when the states change, and it makes bug in your code. The correct way is setting state and track the changed state in your component.

Reza Ghorbani
  • 537
  • 4
  • 14