Updating objects in React State
Just like Props, we should treat state objects as immutable (read-only).
For example, in the following code, we cannot update the property age of the user object in this way: user.age = 24
const [user, setUser] = useState(
{
name: 'Ehsan',
age: '32'
}
)
const handleClick = () => {
user.age = 24;
setUser(user);
}
this way of updating is wrong, and it will not update our state, so the component will not re-render.
* The correct way of updating the state object is to create a new instance of an object with updated property, and then call the setState with this new object:
const handleClick = () => {
const newUser = {
name: 'Ehsan',
age: 24
}
setUser(newUser);
}
Also, we can define the new object as below (spread operator):
const newUser = {
...newUser,
age: 24
}
this syntax will copy all the previous properties and append the updated property.
The more professional way of updating an object in the state is as below (in one line!):
setUser({...user, age: 24});
so, we don't need to define a new object (newUser).
Please note that the spread operator in javascript does shallow copy of objects.
It means that if we want to update a nested object in the state, the spread operator will only copy the first level of the object.
For example, imagine that our user object is as below:
{
fullName: 'Ehsan Safari,
age: 32,
address: {
city: 'Milan',
zipCode: 10123
}
}
now we are going to update the zip code of the user's address. If we just use the spread operator as before, we cannot achieve this goal. So we have to use spread twice as below:
setUser({...user, address: {...user.address, zipCode: 10321}});
#reactjs #state_object #update_object #javascript
Fullstack Developer | PHP lover | Learning Golang
1 年Thanks sir, can you give some recommendations to learning react
Software Developer | Javascript, React, Next.js, Node.js
1 年??? ??? ??? ...newUser ?? ???? ??? ...user