Skip to content

Instantly share code, notes, and snippets.

@Raynos
Forked from jlongster/app.js
Last active August 29, 2015 13:57
Show Gist options
  • Save Raynos/9656088 to your computer and use it in GitHub Desktop.
Save Raynos/9656088 to your computer and use it in GitHub Desktop.
var hash = require('observ-hash')
var array = require('observ-array')
var observ = require('observ')
var dom = React.DOM;
var App = React.createClass({
getInitialState: function() {
// create observable immutable data structure
var state = hash({
todos: array([])
});
var self = this;
self.oState = state;
// on data structure change call setState from
// react to re-render
state(function (currState) {
// currState is plain JS object
self.setState(currState);
});
// return current state
return state();
},
addTodo: function() {
// mutable interface creates new
// immutable data structure and emits it
this.oState.todos.push(hash({
value: observ('todo')
}));
},
updateTodo: function(i, e) {
// call .get() to get item at index
var todo = this.oState.todos.get(i);
// again mutable interface creates new
// immutable data structure
todo.value.set(e.target.value);
},
render: function() {
return dom.div(
null,
dom.button({
onClick: this.addTodo
}, 'click'),
dom.ul(
null,
this.state.todos.map((todo, i) => {
return dom.li(null, TodoItem({
desc: todo.value,
onChange: this.updateTodo.bind(this, i)
}));
})
)
);
}
});
var TodoItem = React.createClass({
shouldComponentUpdate: function(nextProps) {
// won't nextProps *always* be a new object?
// yep. so compare the keys inside it
return this.props.desc !== nextProps.desc;
},
render: function() {
return dom.div(
null,
dom.input({ value: this.props.desc,
onChange: this.props.onChange }),
this.props.desc
)
}
});
React.renderComponent(App(), document.body);

Questions:

I'm trying to understand how to leverage immutability, and have a few questions:

  1. The imperative code in updateTodo is the kind of stuff you can't guarantee people won't do, and is that the reason you have a very conservative shouldComponentUpdate by default? You say never to mutate this.state in the docs, but you assume that people are going to mutate objects within the app state?

  2. I'm having trouble figuring out how to write shouldComponentUpdate even if we update this.state functionally. Won't nextProps always be new, since render creates a new props object every time? How do we compare props and nextProps?

Answers:

  1. You can't mutate. People do because javascript, for perf you must simply not mutate. It's recommended you use some kind of module for mutating stuff but having immutability under the hood like observ-array & observ-hash

  2. nextProps is always a fresh object, so dont compare it, compare the things that can change like desc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment