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>
);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With