I'm trying to implement shouldComponentUpdate on some of my components for sake of performance. We do it the usual way - have an immutable model and do reference comparison. It works for the most part, but I keep wondering if I'm handling functions in props correctly.
Essentially, my question is: in shouldComponentUpdate, what do you normally do with functions in props? Do you ignore them altoghether, or do you try to compare them somehow?
Here's an example:
var Inner = React.createClass({
shouldComponentUpdate(newProps){
return ???
},
render(){
return <div onClick={this.props.onClick} />;
}
});
var Outer = React.createClass({
getInitialState(){ return {value: 0}; },
render(){
var val = this.state.value;
return <div>
<span>{val}</span>
<Inner onClick={() => { this.setState({value: val + 1}) }} />
</div>
}
});
Suppose I need the Inner component to have shouldComponentUpdate (suppose it is rendered many times and it is hard to render). How would you implement it? I tried the following:
1) this.props.onClick === newProps.onClick - works if you keep passing the same method, but it wouldn't work in this example, since the method is created inline.
2) this.props.onClick.toString() === newProps.onClick.toString() - works if the function doesn't have anything stale in closure - wouldn't work here, since val is in the function's closure.
3) As Michael pointed out, you can ignore functions in shouldComponentUpdate, with the same problem as 2) has.
All of these approaches make it possible to introduce subtle bugs, is there a more foolproof way of doing this? I know it's easy to rewrite this example to work, but ideally I'd like to be able to extract the shouldComponentUpdate behavior into a mixin that's as robust as possible, not lending itself to these problems.