Member-only story

How To Properly Change State in React

Steve Pesce
3 min readAug 11, 2020

--

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(). 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()

Given an object obj, setState(obj) will update or create all given key value pairs. For example here is a simple component:

--

--

No responses yet