setState vs replaceState in React.js
Solution 1:
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.
I asserted this with this test case.
If your current state is {a: 1}
, and you call this.setState({b: 2})
; when the state is applied, it will be {a: 1, b: 2}
. If you called this.replaceState({b: 2})
your state would be {b: 2}
.
Side note: State isn't set instantly, so don't do this.setState({b: 1}); console.log(this.state)
when testing.
Solution 2:
Definition by example:
// let's say that this.state is {foo: 42}
this.setState({bar: 117})
// this.state is now {foo: 42, bar: 117}
this.setState({foo: 43})
// this.state is now {foo: 43, bar: 117}
this.replaceState({baz: "hello"})
// this.state. is now {baz: "hello"}
Take note of this from the docs, though:
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.
Same goes for replaceState()