Arrow Functions for attributes

I’m a bit confused about when to use arrow functions vs just a function itself, especially in the case of say using a function for an onClick attribute. AKA:

Why does this work?

function App() { const [count, setCount] = useState(0); return ( <div> <p>{count}</p> <button onClick={() => setCount(count+1)}>Update count!</button> // note how onClick is set here </div> ) } export default App;

…and why does this not work?

function App() { const [count, setCount] = useState(0); return ( <div> <p>{count}</p> <button onClick={setCount(count+1)}>Update count!</button> // note how onClick is set here </div> ) } export default App;

This is a general question but was loosely inspired by this exercise:
https://www.codecademy.com/courses/react-101/lessons/the-effect-hook/exercises/fetch-data

From mdn: syntax is target.onclick = functionRef;

Note here functionRef is a function expression or a function name. But it is not an invocation of a function (such as setCount(count+1)).

1 Like

Or we might just call it what it is, a function reference. It is not a function expression, as such, given it is only a name. Splitting hairs, maybe. It is after all a fine distinction. Just saying.

1 Like