Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (2018) Understanding State Handling Events

IncrementScore Function

Hey, Could someone explain to me why at 2:52, when Guil code the onClick event inside <button>, he calls the incrementScore function but he did not wrote the curly braces (). He explains breathly in that video, I saw that when you user () the fuction is called right when it renders, and without it just when you click, but why is that?

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

He actually doesn't "call" the function. He passes in the function. The function gets called later when someone clicks.

This isn't unique to React, it's also how callback functions work in vanilla JavaScript. A lot of people get tripped up by this, partly because the way we typically learn about even handler callbacks is by passing in an anonymous function in place:

element.addEventListener("click", function(){ 
    alert("Hello World!"); 
});

We see parens () here only because that's part of the syntax of defining a function. We're not calling the function here right away. This code above is exactly the same as this:

function myFunction() {
  alert ("Hello World!");
}

element.addEventListener("click", myFunction);

When I pass in the function myFunction as the event handler, there's no parens. It's a reference to the function, which will be called later when the event is triggered. Here's the same thing with an ES6 arrow function, same result:

const myFunction = () => {
  alert ("Hello World!");
}

element.addEventListener("click", myFunction);

FYI I stole these code snippets from here