Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to create functions in render?

Tags:

reactjs

Is putting functions in render like this a bad practice?

Are these functions created every render, leading to a performance hit? How big of a performance hit? Is there a link somewhere that measures this or a reliable source saying that this is bad?

Does this cause unnecessary renders in any way? I hear this is especially not a good idea for PureComponent.

Having trouble finding clarification whether this is okay or not.

class MyComponent extends Component {
  ...

  render() {
    const myFunc1 = () => {};
    const myFunc2 = () => {};
    const myFunc3 = () => {};
    const myFunc4 = doSomething(() => {});

    return (
      <div>hello world</div>
    );
  }
}
like image 428
atkayla Avatar asked Jun 30 '17 13:06

atkayla


2 Answers

Is putting functions in render like this a bad practice?

Yep

Are these functions created every render, leading to a performance hit?

Yes

How big of a performance hit?

It can vary from totally negligible (most of simple components) to absolutely critical (if you constantly re-render your whole tree on a complex app).

Is there a link somewhere that measures this or a reliable source saying that this is bad?

See Chase DeAnda's answer.

Does this cause unnecessary renders in any way? I hear this is especially not a good idea for PureComponent.

Indeed, since the function will be created at every render, if you pass them to a PureComponent, it will think the function changed and will render again.

Having trouble finding clarification whether this is okay or not.

I hope this helps.

like image 167
Anthony Garcia-Labiad Avatar answered Sep 21 '22 17:09

Anthony Garcia-Labiad


More like a bad practice. It won't break your code, but can cause some serious performance issues. From the React Docs

The problem with this syntax is that a different callback is created each time the component renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.

So what you have in the example is fine because you aren't passing it down as a prop. If you passed myFunc4 to the div as a prop, then you would see some performance issues.

like image 29
Chase DeAnda Avatar answered Sep 21 '22 17:09

Chase DeAnda