Suppose I have a ReactJS component and want to call some custom function in it, is it better to have this function as a class method, or rather defined separately? (suppose that the function should be used only in this component)
class OnwComponent extends React.Component {
constructor() {
super();
this.doubledNumber = this.doubledNumber.bind(this);
}
doubledNumber(num) {
return num * 2;
}
render() {
return (
<p>{doubledNumber(10)} or {this.doubledNumber(10)}? Pros and cons?
);
}
}
function doubledNumber(num) {
return num * 2;
}
This is generally just a style preference.
Having said that, ESlint has exactly this rule: class-methods-use-this:
If a class method does not use this, it can safely be made a static function.
Also, one of the most popular React style guides (airbnb) has this rule enabled by default. So, in terms of best practices I would say: move doubledNumber function out of the class.
In the discussion related to implementing this rule in eslint, they talk about performance considerations too:
This rule is stylistic, but has performance implications. If a function is not using this, it is unnecessarily copied whenever a new instance of the class is created.
It depends.
If the function is related to the component logic itself and used only there, I'd leave it as a component method.
Otherwise:
If the function represents a solution to a generic programming common problem, I'd move it in a helper component, import the helper component in your React component and use it.
If the function is related to a specific business logic, I'd move it inside a service component, that holds the feature business logic, import the service component in your React component and use it.
So, this is primary an opinion based question. Based on your project set-up and the method logic, you need to make the final decision.
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