Why it is not necessary to spread the current state (...this.state) when I handle input change in React Class Component? In current state I have other objects
handleInputChange = (newValue: string) => {
this.setState({
...this.state, *<--- this string*
value: newValue,
});
};
State Updates are Merged
When you call
setState(), React merges the object you provide into the current state.For example, your state may contain several independent variables:
constructor(props) { super(props); this.state = { posts: [], comments: [] }; }Then you can update them independently with separate setState() calls:
componentDidMount() { fetchPosts().then(response => { this.setState({ posts: response.posts }); }); fetchComments().then(response => { this.setState({ comments: response.comments }); }); }The merging is shallow, so
this.setState({comments})leavesthis.state.postsintact, but completely replacesthis.state.comments.