Can I avoid forceUpdate() when using React with Backbone?
backbone.js, javascript, reactjs
Solution
Pete's answer is great.
Backbone models are inherently mutative, which (while not a problem in itself) means that when rerendering, you won't have the old version of the model to compare to. This makes it harder to do intelligent optimizations by defining `shouldComponentUpdate` methods in key places on your components. (You also lose out on the ability to easily store old versions of your model for other reasons, like implementing undo.)
Calling `forceUpdate` merely skips `shouldComponentUpdate` and forces the component to rerender. Note that calling `render` is usually cheap, and React will still only touch the DOM if the output of `render` has changed, so performance problems here aren't common. However, if you have the choice to use immutable data (including passing around raw model property objects from `toJSON()` as Pete suggests), I'd highly recommend it.
Problem
Facebook React encourages you to separate mutable (`state`) and immutable (`props`) state: Try to keep as many of your components as possible stateless. By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application. When the state changes, you are supposed to call `setState` to trigger virtual DOM diff, which will cause a real DOM update only when this is needed. There is a way to trigger DOM update manually by calling `forceUpdate` but it is discouraged: Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient. However, all React+Backbone examples I have seen ignore this advice and store models and collections in `props` and call `forceUpdate`: - http://www.thomasboyt.com/2013/12/17/using-reactjs-as-a-backbone-view.html - https://github.com/usepropeller/react.backbone/blob/master/react.backbone.js - https://gist.github.com/ssorallen/7883081 - http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/ Even React's own example uses `forceUpdate`: - https://github.com/facebook/react/blob/master/examples/todomvc-backbone/js/app.js#L148 Is there a better way, though, and what benefits would it give?