Callback functions in react
Today I’ve been working through React with some students at Manchester Digital, and I had a hard time trying to explain some of common syntax. In particular, callback functions.
<button onClick={() => setCount((count) => count + 1)}>
Personally, I struggle with this kind of minimal syntax until I’ve written it a few times myself. I had the same issue with PHP when they introduced all the shorthand conditionals and that kind of thing, and the same with terraform and pretty much every language under the sun. Especially perl but nobody uses that any more right?
Anyway, I wanted to break down the above code and what it means.
onClick={do whatever is written here when you click on the button}
The () => ... syntax is a function definition. This is normally written like this:
function hello() {
...
}
But instead it’s an anonymous function (it has no name unlike our hello function), the empty parenthesis mean it’s got no arguments in this example. The ellipsis (…) is purely there to show where the body of the function would go.
So from that, we can see there are two functions in the original <button> code:
<button onClick={() => setCount((count) => count + 1)}>
The first function is called when the button is clicked - this is a function that calls setCount. setCount itself doesn’t return anything (undefined).
The second function is setCount. setCount takes the value count in and returns the value of count + 1. We could rewrite setCount like this:
function setCount(count) {
return count + 1;
}
In fact, we could write the whole thing long hand like this (note this may not be valid javascipt but is for illustrative purposes):
function click() {
return function setCount() {
return count + 1;
}
}
<button onClick={click()}>
- You pass a function to
onClick - React stores it
- Later — when the user clicks the button — React calls that function
Simple right? :/