How To Properly Change State in React

When learning React, you will be introduced to the tool React.Component.setState() and instructed to never update the state property directly. In any programming language, if you are provided an accessor method (a getter or a setter), it’s safe to assume that you shouldn’t access the variable directly. This holds true for setState() as well.

Why You Should Never Update State Directly

  • setState() is asynchronous. If you set state directly, it may be overwritten from a call to setState(). setState() can be deferred or batched, so it is hard to say when the state will actually be changed after it is invoked.
  • directly mutating the state will not trigger a re-render, while setState() always re-renders.
  • most importantly — because React tells you not to. Since it is expressly forbidden to mutate the state directly, React will always assume that you are using setState() to change the state. A direct mutation of state is unsupported and may cause bugs and unexpected results.

How to use setState()

React Component Developer Tools

We can use setState() to set a single state prop:

This is inside of a componentDidMount() to ensure that it runs just after initialization

Let’s say instead, we wanted to update the author and title as well as adding an additional ‘year’ state, setState() will create or update the values passed:

React has no problem creating the new ‘year’ state:

Setting Nested State

In order to add a book to this we need to use the spread operator in conjunction with setState() :

And our book has been added to the component:

Similarly, if we want to change something inside of one of the nested objects, we need a deep copy. We can use map() to both copy the original array of objects, as well as change the value of year:

Note: {books} is the same as {books: books}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store