Updating Objects in State
State is also designed to hold J*avaScript Objects*. However, we cannot change the state of objects directly as we did with the other JavaScript values, like numbers, strings, and booleans.
We can change the state of the objects by either
Creating a new object
Or make a copy of the existing object
Mutation, which means changing the properties of a value, is possible in all the React objects. Values like numbers, strings, and booleans are immutable. While using objects we must treat them as immutable or βread-onlyβ.
In the above code the red dot that we are trying to create and whose dimensions are already provided in the styles object does not work in the desired way. The red dot is supposed to move wherever the cursor is positioned but it does not and stays fixed in a particular position.
In the example above, we are trying to directly change the value of the object assigned to the position. This code does not give us the required results as we are not updating the state so react is unaware of the change in state and hence, the dot pointer does not move accordingly.
To fix this issue, we create another object, a new one, and pass it to the state setter function βsetPositionβ.
Without using the state setting function, React is unaware of the change in the state and hence does not re-render the changes. This code modifies the object assigned to the position from the previous render. In the above code, the changes are rendered as the setPosition function updates the variables.
Even though the objects are mutable, we must use the state value that we have to render as read-only. Only then will we get our desired output.
The output given by the above code is:
Top comments (0)