idev0085 / react-boilerplate

0 stars 0 forks source link

What is the difference between setState and replaceState? #99

Open idev0085 opened 2 years ago

idev0085 commented 2 years ago

With setState the current and previous states are merged. With replaceState, it throws out the current state, and replaces it with only what you provide. Usually setState is used unless you really need to remove keys for some reason; but setting them to false/null is usually a more explicit tactic.

While it's possible it could change; replaceState currently uses the object passed as the state, i.e. replaceState(x), and once it's set this.state === x. This is a little lighter than setState, so it could be used as an optimization if thousands of components are setting their states frequently.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

According to the docs, replaceState might get deprecated:

This method is not available on ES6 class components that extend React.Component. It may be removed entirely in a future version of React.