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: