Is there a better way to avoid re-creating a function when rendering

We know that it is recommended to avoid the arrow / link / create functions inside render, because these functions will be recreated on every render.

Given the following possible ineffective component:

const MyComponent = ({ ItemId, onSomeEvent }) => 
{
  return <SomeOtherComponent onSomeEvent={ val => onSomeEvent(itemId, val) } />;
};

I would probably rewrite this as:

const MyComponent = React.createClass({
  someItemId: 0,
  onSomeEvent: () => {},
  someHandler(emittedValue){
    this.onSomeEvent(this.someItemId, emittedValue);
  }
  componentDidMount() {
    const { itemId, onSomeEvent } = this.props;
    this.someItemId = itemId;
    this.onSomeEvent = onSomeEvent;
  },
  render() {
    <SomeOtherComponent onSomeEvent={ this.someHandler } />
  };
});

The only reason I do this is to avoid re-creating the function in the rendering method. What is the best way to do this? The way I do it seems too verbose. Thoughts?

+4
source share
1 answer

You do not need to assign a function to componentDidMount. You can directly call the props function.

const MyComponent = React.createClass({
  propTypes: {
    itemId: React.PropTypes.number.isRequired
    onSomeEvent: React.PropTypes.func.isRequired
  },
  someHandler(emittedValue){
    this.props.onSomeEvent(this.props.itemId, emittedValue);
  }
  render() {
    <SomeOtherComponent onSomeEvent={ this.someHandler } />
  };
});

, prop, :)

0

All Articles