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 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.
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