I am new to React.js Library and I was going over some of the tutorials and I came across:
this.setState
this.replaceState
The Description given is not very clear (IMO).
setState is done to 'set' the state of a value, even if its already set in the 'getInitialState' function.
Similarly,
The replaceState() method is for when you want to clear out the values already in state, and add new ones.
I tried this.setState({data: someArray});
followed by this.replaceState({test: someArray});
and then console.logged them and I found that state
now had both data
and test
.
Then, I tried this.setState({data: someArray});
followed by this.setState({test: someArray});
and then console.logged them and I found that state
again had both data
and test
.
So, what exactly is the difference between the two ?
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.
State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
shouldComponentUpdate() Safe to use setState ? Yes! This method is called whenever there is an update in the props or state. This method has arguments called nextProps and nextState can be compared with current props and currentState .
The render() function should be pure, meaning that it does not modify a component's state. It returns the same result each time it's invoked, and it does not directly interact with the browser. In this case, avoid using setState() here.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With