I know that an error is thrown when setting state for a component not yet mounted. Which explains the error I get from using setState function as oppose to explicitly and directly setting the state.
import React, {Component} from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {term: ''}; // -> seems to be the agreed means to set initial state
// this.setState({term: ''}); // -> generates an error
}
render() {
return (
<div>
<input onChange={event => this.setState({term: event.target.value})}/>
Value of the input: {this.state.term}
</div>
);
}
}
The error I get when I uncomment the second line this.setState({term: ''}) is:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the component.
I know how to prevent the error, simply by setting state explicitly without telling React anything about it and I have already seen the github issue talking about the bug: Github Issue #3878 What I want to know though is why cant React work it out? if one calls setState from a constructor it knows this is the first time its being used? I am probably simplifying it way too much, but if anyone has a nice technical answer as the reason why not?
setStatetriggers a long and complicated process of delayed re-rendering. As a wild guess - they just did not want to complicate the process (even further) that would in turn give 0 benefits.