DEV Community

MZ
MZ

Posted on • Updated on

Different ways of calling a function in a React class

Let's take a look at this class.

class Clock extends React.Component {
    constructor(props) {
        super(props);

        this.state = {date: new Date()};
    }

    componentDidMount() {
        this.timer = setInterval(() => (this.tick()), 1000);
    }

    tick() {
        this.setState({date: new Date()});
    }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    render() {
        return(
            <div>
                <h1>Clock</h1>
                <h1>It is {this.state.date.toLocaleTimeString()}.</h1>
            </div>
        );
    }
}

ReactDOM.render(<Clock />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

As you can see, this is a <Clock /> class.

First Question:

this.timer = setInterval(() => (this.tick()), 1000);
Enter fullscreen mode Exit fullscreen mode

Why does this work instead of, say:

this.timer = setInterval(this.tick(), 1000);
Enter fullscreen mode Exit fullscreen mode

The first one sets a function as a callback to the first argument of setInterval and actually calls the function in the callback.

The second invokes the function on load.

Second Question:

Let's say I want to put the code as:

this.timer = setInterval(this.tick, 1000);
Enter fullscreen mode Exit fullscreen mode

Can you? Yes, you can.

You would have to bind the function in the constructor.

constructor(props) {
        super(props);

        this.state = {date: new Date()};

        this.tick = this.tick.bind(this)
    }
Enter fullscreen mode Exit fullscreen mode

Why? Well, you actually have to call the function and that is what binding does behind the scenes.

However, if you don't want to explicitly bind the function, you can declare it using the ES6 arrow syntax.

tick = () => {
    this.setState({date: new Date()});
}
Enter fullscreen mode Exit fullscreen mode

This achieves the same effect of binding.

Thus, you can still do this, without having to explicitly bind the function.

this.timer = setInterval(this.tick, 1000);
Enter fullscreen mode Exit fullscreen mode

If you want to know more about binding, I will refer you to this very comprehensive guide on binding. It got technical pretty fast for me, so take your time.

If you're wondering how I found it, I was looking through the React website and found the link.

I hope it helps you!

Top comments (0)