React setState function prevState mutation
Starting point for creating JSFiddles with React.
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="react"></div>
Babel + JSX
class Test extends React.Component {
state = { counter: 0 };
onDemonstrateButtonClick = (event) => {
this.setState((prevState) => {
if (prevState === this.state) {
alert(
`
The prevState object reference is the same as the this.state object reference
meaning the this.state object instance is passed as a parameter to setState
and since this.state should not be mutated directly, it follows setState's
prevState shouldn't either?
Also this function is kind of a like a Redux reducer where you are not supposed
to mutate the state object directly either, but instead return a clone of it.
So what's up?
`
);
}
prevState.counter++;
return prevState;
});
};
render() {
return (
<div>
<button onClick={this.onDemonstrateButtonClick}>Demonstrate</button>
<br />
{this.state.counter}
</div>
);
}
}
ReactDOM.render(<Test />, document.getElementById('react'));