Given the below react component.
function App() {
const [text, handleTextChange] = useState('Some Text');
const handleChange = () => {
handleTextChange('Button handler clicked');
}
return (
<>
<span>{text}</span>
<button onClick={handleChange}>Change Text</button>
</>
)
}
In the above component we can write onClick handler in two different ways
<button onClick={handleChange}>Change Text</button>
and
<button onClick={() => handleChange()}>Change Text</button>
which approach is better and why ?
2
Answers
Both will work, and in this case, both will functionally be pretty much the same.
In your first example, you’re directly passing the function reference to
onClick
In your second example, you’re passing an anonymous function to
onClick
. When called, that anonymous function callshandleChange
Unless you’re getting some parameters passed to
handleChange
that you don’t want to, I’d suggest not wrapping it in an anonymous function like your second example. There’s no benefit to it. It’s just overhead.In the 2nd example you’re creating 2 functions, we usually would want that in case we want to pass dynamic data to the inner function.
For example
In this example we are passing a function reference:
But lets say you want to add a dynamic data, for example when iterating over a loop and you want to pass the index of each item: