Javascript – Event Handlers in React Stateless Components

javascriptreactjs

Trying to figure out an optimal way to create event handlers in React stateless components. I could do something like this:

const myComponent = (props) => {
    const myHandler = (e) => props.dispatch(something());
    return (
        <button onClick={myHandler}>Click Me</button>
    );
}

The drawback here being that every time this component is rendered, a new "myHandler" function is created. Is there a better way to create event handlers in stateless components that can still access the component properties?

Best Answer

Applying handlers to elements in function components should generally just look like this:

const f = props => <button onClick={props.onClick}></button>

If you need to do anything much more complex it's a sign that either a) the component shouldn't be stateless (use a class, or hooks), or b) you should be creating the handler in an outer stateful container component.

As an aside, and undermining my first point slightly, unless the component is in a particularly intensively re-rendered part of the app there's no need to worry about creating arrow functions in render().