What is the correct way to access props in the constructor ? Yes i know that in the React documentation is said that
When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs
To be more clear , why do wee need this.props
if we can just use props inside constructor
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(props)
// -> { something: 'something', … }
// absolutely same
console.log(this.props)
// -> { something: 'something', … }
}
}
Are there some cases when to use props
over this.props
?
this.props
and props
are interchangeable in constructor because this.props === props
, as long as props
is passed to super
. The use of this.props
allows to detect a mistake instantly:
constructor() {
super();
this.state = { foo: this.props.foo }; // this.props is undefined
}
Consistent use of this.props
makes it easier to refactor constructor body:
constructor(props) {
super(props);
this.state = { foo: this.props.foo };
}
to
state = { foo: this.props.foo };
Only this.
needs to be removed.
There are also typing problems with props
in TypeScript, this makes this.props
preferable for typed component.
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