I am learning about react components following the documentation https://facebook.github.io/react/docs/state-and-lifecycle.html
Why do we need to use arrow function
The simple answer to that is that the tick function needs to be able access the context of its use/ this
, which is the Clock component. In other words it needs to be bound to the Clock component so that it works in the context of the Clock component and not the global context which is everything outside of the Clock component.
Functions within React classes are not bound by default and failure to bind the function will return undefined
instead of the expected result.
There are several ways to bind the tick function to the Clock component example from the Reactjs website.
Arrow functions can access this
which is why they are used in the example. In other words, writing an arrow function implicitly means it binds its contents to the local context (the Clock component in this case). Read more on that in this Medium article
Bind the tick function in the constructor
class Clock extends React.Component{
constructor(props){
super(props);
this.state={date: new Date()}
this.tick=this.tick.bind(this)
}
componentDidMount() {
this.timerID = setInterval(this.tick.bind(this),
1000
);
}