In a typical class-based React component, this is how I would create an event handler:
class MyComponent extends Component {
handleClick = () => {
...
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
However, I find myself with two options when I use a hooks-based functional paradigm:
const MyComponent = () => {
const [handleClick] = useState(() => () => {
...
});
return <button onClick={handleClick}>Click Me</button>;
};
or alternatively:
const MyComponent = () => {
const handleClick = useRef(() => {
...
});
return <button onClick={handleClick.current}>Click Me</button>;
};
Which one is objectively better, and for what reason? Is there another (better) way that I have not yet heard of nor discovered?
Thank you for your help.
Edit: I have put an example here on CodeSandbox showing both methods. Neither seems to unnecessarily recreate the event handler on each render, as you can see from the code on there, so a possible performance issue is out of the question, I think.