I know functional components are easier to use than class components but I'm trying to learn doing things using both of them to understand better. So I looked up some examples at official react website.
The Timer example at reactjs.org/#a-stateful-component adds seconds as a state of component but it adds interval directly on as property of this.
I wonder if there is difference between both approaches? When should I add a property on this instead of adding it as a state?
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 }; //adding as state
}
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000); //added property on this
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
</div>
);
}
}
General rule of thumb is. If you want something to change in UI. You update it in state if no UI change is required. You just update the property