Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Should I use class method or external function

Tags:

reactjs

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;
}
like image 268
user3696212 Avatar asked Sep 06 '26 09:09

user3696212


2 Answers

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.

like image 129
SM79 Avatar answered Sep 08 '26 06:09

SM79


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.

like image 20
Kaloyan Kosev Avatar answered Sep 08 '26 05:09

Kaloyan Kosev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!