React constructor() Method
The constructor() method has the following format:
constructor(props)
Before a React component is mounted, its constructor function constructor() is called.
When a React.Component subclass implements a constructor, super(props) should be called before any other statements.
In the following example, React calls the constructor when creating the component:
Example
class
Header
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
favoritewebsite
:
"
runoob
"
}
;
}
render
(
)
{
return
(
<
h1
My favorite website
{
this
.
state
.
favoritewebsite
}
h1
)
;
}
}
Try it »
In React, a constructor is only used in the following two cases:
- Initializing internal state by assigning an object to this.state.
- Binding instances for event handler functions.
If you do not initialize state or bind methods, there is no need to implement a constructor for the React component.
Do not call the setState() method in the constructor() function. If your component needs to use internal state, assign the initial state directly to this.state in the constructor:
constructor(props) {
super(props);
// Do not call this.setState() here
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
You can only assign to this.state directly in the constructor. To assign in other methods, you should use this.setState() instead.
React Component Lifecycle