Safe to set on this.state just to keep track?

- 1 answer


I was wondering if it is safe to set .state when I need to keep track.

My component, allows user to click it, every time they do it increments tieId. On mouse exit of the component, if the tieId is different from when they mouse enetered the component, I want to do a save.

I had to keep track on this.state

Is this code approptiate or will it break the React diff checking as I didn't use this.setState{tieId: ...}?

var HelloMessage = React.createClass({
    getInitialState: function() {
        return {tieId: -1, onEnt: -1};
    click: function(e) {
        if (this.state.tieId > 2) {
            this.state.tieId= -1;
    mouseEnter: function(e) {
        this.state.onEnt = this.state.tieId
    mouseLeave: function(e) {
        if (this.state.tieId != this.state.onEnt) {
            alert('ok saving');
        } else {
            alert('will not save because tie id is same as when entered \n tieId: ' + this.state.tieId + ' \n onEnt: ' + this.state.onEnt);
  render: function() {
    return <div onClick={} onMouseLeave={this.mouseLeave} onMouseEnter={this.mouseEnter} >Hello </div>;

ReactDOM.render(<HelloMessage />, mountNode);

Can copy paste this code at the React site Live JSX editor -




You should always use setState() to make changes to your component state in React.

In case you don't believe me, here's Dan Abramov saying the same thing :)

(There's an exception if you're using ES6 classes: your constructor should set state directly.)