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:-
getName
and getMessage
at every render
call.getName
and getMessage
class methods and call them inside renderMessage
would it be an improvment?Thanks :)
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 are defining at this scope will be part of this scope only. In your case, the functions getMessage
and getName
will be part of renderMessage
which is functional scope.
At every call, new functions are getting defined instead of reusing previously defined functions.
If I make getName and getMessage class methods and call them inside renderMessage would it be an improvement?
Depends.
If this function need access to any component properties or method then you should place it inside the component or if this is the only utility function then place it inside a helper library separate from the component. Surely, this will make difference.