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.
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.
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!
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.
A constructor is called every time the component is mounted, not only once.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With