Skip to content

Instantly share code, notes, and snippets.

@ethan-deng
Last active October 9, 2016 03:50
Show Gist options
  • Save ethan-deng/2e5cbaeabefdddc7a4fc to your computer and use it in GitHub Desktop.
Save ethan-deng/2e5cbaeabefdddc7a4fc to your computer and use it in GitHub Desktop.

React.js State Explained

var React = require('react');
var $ = require('jquery');
/********************************************************
This code is to explain state mutation in React and demo
why immutable.js is a better approach
**********************************************************/
var Test = React.createClass({
  getInitialState: function(){
    return {
      // state is not a simple type but a object type
      content: {a:1, b:2}
    };
  },
  render: function () {
    return (
        <div className="">
          <h1>Hello World</h1>
          // print out the content of the state
          <h2>{JSON.stringify(this.state.content)}</h2>
          <button type="button" onClick={this.mutateState}>Click Me!</button>
        </div>
    );
  },
  // shouldComponentUpdate: function(nextProps, nextState) {
    // A: even content.b is set to 2, this will result false since deep copy
    // B: The reference to object doesn't change and the comparing of states will always return false
    // if (nextState.content === this.state.content){
    //   return false;
    // }
    // else{
    //   return true;
    // }
  // },
  mutateState: function(){
    // chose to run A, B, or C by commeting out code
    // A:
    // Standard way of mutation of object is to treat the object as immutable and do deep copy of the state
    // The result is {"a":1,"b":2} -> click -> {"a":1,"b":2000}
    var content = $.extend(true, {}, this.state.content);
    content.b = 2000;
    this.setState({
      content: content
    });

    // B:
    // Direct mutation of the object is not recommended but it works too.
    // The problem with approach is that shouldComponentUpdate will not possible since the mutation is in place
    // The reference to object in state doesn't change
    this.state.content.b = 2000;
    // trigger UI update
    this.setState({});

    // C:
    // A little bit dfferent code but is actually exactly same as B
    this.state.content.b = 2000;
    this.setState({
      content : this.state.content
    })

    // D:
    // immutable.js avoid the deep copy and the issue of comparing reference of B/C
  }
});

module.exports = Test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment