ReactJS Set State Of An Array
When you try to set state of an array value then you face that behaviour: state doesn’t change. But you’re sure for change content of array like that:
function User() { const [users, setUsers] = useState([ { id: 1, name: 'Emir' }, { id: 2, name: 'Bugra' } ]) function updateUser(id, name) { const user = users.find(user => user.id === id) user.name = name console.log('updated users:', users) setUsers(users) } // ... continuing code ... }
In console you can see that you set users array correctly. But React doesn’t update state and doesn’t re-render the component. So what is the problem? Problem is about reference. Arrays passes by reference to a function/method and if you pass same reference then ReactJS doesn’t update the state and doesn’t apply re-render. In this example you’re working on same reference array and because of this ReactJS doesn’t apply re-render. For solving this problem you must create brand new array and pass it as new state. You have two ways for creating a new array.
Using Spread Operator
In Javascript you can put an array to another like that: “put all content as seperated”. With this way you can create brand new array reference with coping content in single line and very easy:
const newUsers = [...prevUsers]
Now apply this code to our updateUser() function:
...... function updateUser(id, name) { const newUsers = [...prevUsers] // create brand new array with content const user = newUsers.find(user => user.id === id) user.name = name console.log('updated users:', newUsers) setUsers(newUsers) } ......
As you can see we created brand new array which name is newUsers and modify it and set as new state. Now as you can see the state and the re-render problem solved.
Using Array.prototype.map()
There is a different buy a little expensive method for creating new array. You can map an array with/without changing content for creating brand new array.
const newUsers = users.map(item => item)
This code is same as before. This is only creating brand new array, actually we can put our logic in this syntax like that:
const newUsers = users.map(item => { if (item.id === id) item.name = name }) setUsers(newUsers)
Happy coding…
0 yorum