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
There are a few reasons to never update state directly:
setState()is asynchronous. If you set state directly, it may be overwritten from a call to
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
- 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()
Given an object obj,
setState(obj) will update or create all given key value pairs. For example here is a simple component:
We can use
setState() to set a single state prop:
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
If you want to add to an array in state, you will need to first get a deep copy of the state prop that you want to change. Consider this Books component:
In order to add a book to this we need to use the spread operator in conjunction with
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: