3 ms·
The docs for setState say that if passed an object it will merge the current state and the object. So just do: setState({ a: 4 }) https://reactjs.org/docs
by drdec 5y ago
The docs for setState say that if passed an object it will merge the current state and the object. So just do:
setState({ a: 4 })
https://reactjs.org/docs/react-component.html#setstate https://reactjs.org/docs/react-component.html#setstate
- loh 5y agoThe docs you linked to are for class components (`this.setState`), not function components using hooks (`useState`). From React's "Using the State Hook" docs: > However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it. https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables https://reactjs.org/docs/hooks-state.html#tip-using-multiple... The `extendState` method gives you the same convenience of `this.setState` but with hooks in function components instead of class components.
- drdec 5y agoThanks for the clarification. I was replying to the poster who was using: setState({...state, a: 4}) and so I assumed they were already operating in a class component.