DEV Community

SavvyShivam
SavvyShivam

Posted on

Updating Objects in State

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

  1. Creating a new object

  2. 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:

https://codesandbox.io/s/updating-objects-drbtwm

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay