Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

318
Visualizações
ReactJS - Should I use class method or external function

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;
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda