Is it a good approach to do? Won't it redeclare method getName and getMessage at every render call.
It will redecleare functions getName and getMessage at every render call. It's not great, but not terrible. This approach reduces bugs with rerendering - the function declaration is part of the render result. Although in your exact case it doesnt matter, as the functions will always return the same result and it doesnt depend on the state (although in that case it'd be more readable to just inline the strings)
If I make getName and getMessage class methods and call them inside renderMessage would it be an improvment?
It will make virtual life easier for the garbage collector. The chances are, once you start depending on global state, this will start to go wrong, e.g.:
class App extends React.Component {
getMessage => () {
return "Hello"
}
getName => () {
return this.props.name
}
renderMessage = () => {
someHttpAction().then(() => {
alert(getMessage() + ' ' + getName());
})
}
render() {
return (
<div onclick={this.renderMessage}>Say my name! (Hint, its {this.props.name})</div>
)
}
}
(Note that name is passed in as an argument to App)
When you render the first time, you might expect that, after clicking the text, you'll see an alert of "Hello Vijay". That's true, most of the time. But what happens if, after you click the text, you rerender with a different value for name, say Heisenberg, while someHttpAction promise still has not resolved? You might expect to see your name - Vijay, but actually you'll see the new value, "Hello Heisenberg". By declaring the function inline (as per your example), the function's scope is locked and you'll get the expected result "Hello Vijay".
Imagine a bit more complex scenario where you switch between multiple user profiles and the async messages start showing up on the wrong user...
While yes, we could pass name as an argument to getName, in reality, people think "its fine this time" or forget, and this is how bugs get introduced. Much less difficult to make the same mistake with inline functions. Unless this becomes a bottleneck, stick with the less errorprone approach.
Also, I suggest skimming through How Are Function Components Different from Classes?
getMessageandgetNameonly insiderenderMessage, is that what you're trying to do? That goal would make senserenderMessagewould it be fair to make them a class method as no one is going to use them exceptrenderMessage.