Both of these classes do the same thing, but ClassA seems redundant because of the binding you have to do every time you declare a function and ClassB doesn't seem as clean as ClassA because of the differences in types of function creations.
class ClassA extends React.Component {
constructor() {
super();
this.state = { message: "bar" };
this.foo = this.foo.bind();
}
foo() {
console.log(this.state.message);
}
render() {
return <SomeComponent foo={this.foo} />;
}
}
class ClassB extends React.Component {
constructor() {
super();
this.state = { message: "bar" };
}
foo = () => {
console.log(this.state.message);
}
render() {
return <SomeComponent foo={this.foo} />;
}
}
To get rid of the function creation differences in ClassB, you can probably do something like this, where everything is an expression.
class ClassC extends React.Component {
state = { message: "bar" }
foo = () => {
console.log(this.state.message);
}
render = () => {
return <SomeComponent foo={this.foo} />;
}
}
What are the pros and cons between function declarations and expressions in this case? Are there any performance, memory or even maintainability differences?
Edit: I guess with today's standard technology, the performance difference isn't very noticeable. I guess what I really want out of this question is what is the best practice for creating functions for a class (particularly React component)