In a React component, props are variables passed to it by its parent component. State on the other hand is still variables, but directly initialized and managed by the component. The state can be initialized by props. and any other method in this class can reference the props using this.
State is a plain JavaScript object used by React to represent an information about the component's current situation. It's managed in the component (just like any variable declared in a function).
The reason is if you useState it rerenders the view. Variables by themselves only change bits in memory and the state of your app can get out of sync with the view. In both cases a changes on click but only when you use useState the view correctly shows a 's current value.
I suggest storing it on the instance but not in its state
. Whenever state
is updated (which should only be done by setState
as suggested in a comment), React calls render
and makes any necessary changes to the real DOM.
Because the value of timeout
has no effect on the rendering of your component, it shouldn't live in state
. Putting it there would cause unnecessary calls to render
.
In addition to what @ssorallen said, you should also remember to handle the component unmounting before your handleLeave is called.
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);
},
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With