0

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)

Vongdarakia
  • 379
  • 1
  • 12
  • 25
  • @scott-marcus I edited my question to explain that it's more about best coding practices than just performance. Can you remove the duplicate status, please? – Vongdarakia Sep 29 '17 at 20:07
  • The "function declaration and function expression performance difference" link didn't really answer my question :( – Vongdarakia Sep 29 '17 at 20:15
  • For best practice questions, you'd want to post on https://codereview.stackexchange.com. Stack Overflow is for particular programming quesitons. – Scott Marcus Sep 29 '17 at 20:16
  • @ScottMarcus Thanks! Didn't even know that existed! – Vongdarakia Sep 29 '17 at 20:17

0 Answers0