Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 716
user3802738 Avatar asked May 05 '17 23:05

user3802738


People also ask

Is constructor required in React?

If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement.

Why super is used in constructor React?

super() will call the constructor of its parent class. This is required when you need to access some variables from the parent class. Hope this helps!

Can we use constructor in functional component in React?

Therefor you can't specify a constructor . You have to extend React. Component to create a stateful component which then will need a constructor and you'll be able to use the state . Update Since React 16.8.

How many times constructor is called in React?

A constructor is called every time the component is mounted, not only once.


1 Answers

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.

like image 69
loganfsmyth Avatar answered Sep 18 '22 18:09

loganfsmyth