I always write React code, particularly in ES6 Classes. But my question is, when do we use constructor(props)
in React Components? Does the constructor(props)
line has something to do with the rendering of the component together with its props?
The accepted answer is incorrect (perhaps just a misuse of the word "render").
As I explain in my comment on it the constructor of a React component is executed once the first time the component is mounted, or instantiated. It is never called again in subsequent renders.
Typically the constructor is used to set-up a component's internal state
, for example:
constructor () {
super()
this.state = {
// internal state
}
}
Or if you have the class property syntax available (e.g. via Babel) you can forgo declaring a constructor if all you are using it for is to initialise the state:
class Example extends React.Component {
state = {
// internal state
}
}
Does the constructor(props) line has something to do with the rendering of the component together with its props?
The constructor does not directly dictate what is rendered by a component.
What is rendered by a component is defined by the return value of its render
method.
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