Renderless Components

Using components to deal with non-presentational concerns is an extremely powerful pattern that is often overlooked.

One example we use in Shopify is the <EventListener /> component, which is a useful component for adding event listeners on window that automatically manages adding the listeners on mount and cleaning them up on un-mount.

Its implementation looks something like this, though we’ve simplified it a little for the sake of this example:

class EventListener extends React.Component {
  static propTypes = {
    eventName: PropTypes.string,
    handler: PropTypes.func,
  };

  componentDidMount() {
    const {eventName, handler} = this.props;
    window.addEventListener(eventName, handler);
  }

  componentWillUnmount() {
    const {eventName, handler} = this.props;
    window.removeEventListener(eventName, handler);
  }

  render() {
    return null;
  }
}

Last updated