loading...

Function expression vs Function invocation in a class context

muhdmirzamz profile image MZ ・1 min read

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'));

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

First Question:

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

Why does this work instead of, say:

this.timer = setInterval(this.tick(), 1000);

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);

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)
    }

Why? Well, you actually have to call the function. So 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!

Posted on by:

muhdmirzamz profile

MZ

@muhdmirzamz

Software engineer based in Singapore

Discussion

markdown guide