Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring function inside function in React

I just came across a React code and I'm not sure whether it's is a good way to do it or not. This is a sample implementation of that code.

class App extends React.Component {
  renderMessage = () => {
    function getMessage() {
      return "Hello"
    } 
    function getName() {
      return "Vijay"
    }
    return (
      <h1>{getMessage()} {getName()} !!!</h1>
    )
  }
  render() {
    return (
      <div>
        {this.renderMessage()}
      </div>
    )
  }
}

Here we are calling a function renderMessage inside render. In renderMessage there are two inner functions which are called inside renderMessage only. My question now are:-

  • Is it a good approach to do? Won't it redeclare method getName and getMessage at every render call.
  • If I make getName and getMessage class methods and call them inside renderMessage would it be an improvment?

Thanks :)

like image 340
vijayscode Avatar asked Aug 28 '19 05:08

vijayscode


1 Answers

Is it a good approach to do? Won't it redeclare method getName and getMessage at every render call

Definitely not a good approach. As JavaScript is either having functional or block or global scope. Whatever you defining at this scope will be part of this scope only.In your case, these function getMessage and getName will be part of renderMessage which is functional scope.

At every call, new functions are getting defined instead reusing previously defined.

If I make getName and getMessage class methods and call them inside renderMessage would it be an improvement?

Depend. If this function need an access to any component properties or method then you should place it inside the component or If this is only utility function then place it inside helper library separate from component. Surely, this will make difference.

like image 60
RIYAJ KHAN Avatar answered Sep 30 '22 13:09

RIYAJ KHAN