All JavaScript event handlers use an anonymous callback function, this isn’t a React-specific thing: JS uses callbacks to allow you to do one thing (pick up a click event for example) then do another thing (fire a handler function). React follows the exact same pattern, as it’s how the language APIs work:
element.addEventListener("click", () => doThing())
The event handler takes a function, not the value of a function. When the event occurs, the function gets called.
onClick={() => setCount(count + 1)}
When the button gets clicked, execute that function. When that function gets executed, setCount is ran.
If you wrote it like this:
onClick={setCount(count + 1)}
That isn’t a function, it’s the result of a function (which in this case is undefined
, which is not an executable thing).
The callback function optionally takes an argument, which is the Event
object created when the click event happens:
onClick={(event) => setCount(count + 1)}
You aren’t using that event object here, so you can just ignore it
Re the removal of the wrapping function: this isn’t anything special. The event takes a callback function, so you can pass any function you want. But if you did this:
onClick={setCount}
That’s passing a function as the handler (which is fine!), but it’ll do the same as this:
onClick={(event) => setCount(event)}
Which is not fine, as it’ll set count
to be the event object.