Like others said, you should do like you did in your first example.
It's rare that prevState => ({isToggleOn: !prevState.isToggleOn})
will yield a different result than that of {isToggleOn: !this.state.isToggleOn}
, but it can happen.
It's generally recommended to always use the updater function whenever you are setting a new state that depends on the value of the old state.
Here are two snippets that demonstrate what can happen:
Passing an object to setState
Here, despite increasing the counter twice with setState
it only increments by 1 each time.
class App extends React.Component {
constructor() {
super();
this.state = {counter: 0};
this.increment = this.increment.bind(this);
}
increment() {
this.setState({counter: this.state.counter + 1});
this.setState({counter: this.state.counter + 1});
}
render() {
return (
<div>
<h3>{this.state.counter}</h3>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Passing an function to setState
Here, the counter increments correctly by 2.
class App extends React.Component {
constructor() {
super();
this.state = {counter: 0};
this.increment = this.increment.bind(this);
}
increment() {
this.setState(prevState => ({counter: prevState.counter + 1}));
this.setState(prevState => ({counter: prevState.counter + 1}));
}
render() {
return (
<div>
<h3>{this.state.counter}</h3>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>