user3802738
user3802738

Reputation: 117

Constructor Method in React

I have read the React Docs regarding the constructor method and what it can be used for as far as setting state and binding functions but is it really necessary in most cases?

What's the difference between doing

export default class MyClass extends Component {
    constructor(props) {
        super(props);
        this.state = {
            foo: 'bar',
        };
        this.member = 'member';
        this.someFunction = this.anotherFunction(num);
    }
    anotherFunction = (num) => num * 2;
    render() {
        // render jsx here
    }
}

and simply putting all that outside the constructor like

export default class MyClass extends Component {
    state = {
        foo: 'bar',
    };
    member = 'member';
    someFunction = this.anotherFunction(num);
    anotherFunction = (num) => num * 2;
    render() {
        // render jsx here
    }
}

Is one option preferred over the other and are there any performance issues I should know about? This has been bugging me for a bit and I can't seem to find a concrete answer out there.

Upvotes: 5

Views: 887

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161447

Your two examples are functionally identical, but the key thing is that assigning things outside of class methods, but inside of body of a class, like you have with everything other than render and constructor, is not standard ES6, and will only work via Babel. That syntax is the proposed class property syntax.

Upvotes: 5

Related Questions