Why are we calling function without parenthesis ()

Tell us what’s happening:
I’m curious why when rending, we use
{this.addItem}
instead of
{this.addItem()}

Is that a javascript thing that I’ve missed this whole time or is it a React thing?

Your code so far


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      itemCount: 0
    };
    // change code below this line
  this.addItem = this.addItem.bind(this);
    // change code above this line
  }
  addItem() {
    this.setState({
      itemCount: this.state.itemCount + 1
    });
  }
  render() {
    return (
      <div>
        { /* change code below this line */ }
        <button onClick={this.addItem}>Click Me</button>
        
        { /* change code above this line */ }
        <h1>Current Item Count: {this.state.itemCount}</h1>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36.

Link to the challenge:

What the code is saying is that onClick, run the function referenced by {this.addItem} which is addItem(), so there is no need to put (); in fact, doing so would run the function automatically, rather than only after a click.

So include () if you need the function to run automatically, otherwise don’t include them.

2 Likes

Thank you for the explanation.