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 Remove Items From State

Jay McCormick
Jay McCormick
6,646 Points

Anonymous Function in OnClick

Why did we have to use an anonymous function in the button's onClick attribute to call handleRemovePlayer? Why could we not call it directly, as

<button onClick={handleRemovePlayer}>x</button>

?

1 Answer

If you do that, then the method gets invoked immediately when refreshing your react app. That means that there will be no players left because the method already deleted every player.

When you use () => {} then it only gets invoked when clicked on the button.