Instance state variables v in a .js reaction

In response.js, is it better to store the timeout link as an instance variable (this.timeout) or a state variable (this.state.timeout)?

React.createClass({ handleEnter: function () { // Open a new one after a delay var self = this; this.timeout = setTimeout(function () { self.openWidget(); }, DELAY); }, handleLeave: function () { // Clear the timeout for opening the widget clearTimeout(this.timeout); } ... }) 

or

 React.createClass({ handleEnter: function () { // Open a new one after a delay var self = this; this.state.timeout = setTimeout(function () { self.openWidget(); }, DELAY); }, handleLeave: function () { // Clear the timeout for opening the widget clearTimeout(this.state.timeout); } ... }) 

both of these approaches work. I just want to find out the reasons for using one over the other.

+73
javascript reactjs
Aug 08 '14 at 16:09 on
source share
2 answers

I suggest storing it on an instance, but not in state . Whenever state updated (which should only be done by setState , as suggested in the comment), React calls render and makes any necessary changes to the real DOM.

Since the timeout value does not affect the rendering of your component, it should not reside in state . Putting there will result in unnecessary render calls.

+111
Aug 08 '14 at 17:17
source share

In addition to what @ssorallen said, you should also remember to handle unmounting components before calling handleLeave.

 React.createClass({ handleEnter: function () { // Open a new one after a delay this._timeout = setTimeout(function () { this.openWidget(); }.bind(this), DELAY); }, handleLeave: function () { // Clear the timeout for opening the widget clearTimeout(this._timeout); }, componentWillUnmount: function(){ // Clear the timeout when the component unmounts clearTimeout(this._timeout); }, ... }); 
+9
Aug 08 '14 at 20:50
source share



All Articles