Event Handlers in React Stateless Components

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().


Using the new React hooks feature it could look something like this:

const HelloWorld = ({ dispatch }) => {
  const handleClick = useCallback(() => {
    dispatch(something())
  })
  return <button onClick={handleClick} />
}

useCallback creates a memoised function, meaning a new function will not be regenerated on each render cycle.

https://reactjs.org/docs/hooks-reference.html#usecallback

However, this is still at proposal stage.