Component assembly (constructor, componentDidMount)
The assembly of the component is the first phase of the lifecycle of a React component. During this phase, the component is created and inserted into the DOM. Two main methods are used here: constructor
and componentDidMount
.
Constructor
The constructor
is the first method called when a class component is instantiated. It is used to initialize the component’s state and bind methods.
The constructor
receives props
as a parameter and must call super(props)
to ensure this.props
is defined.
Here is a simple example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
// Initialize the state
this.state = {
count: 0,
};
// Bind methods
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
componentDidMount
The componentDidMount
method is called immediately after the component is mounted in the DOM. This is the ideal place to make network requests, subscribe to events, or initiate interactions with external APIs. Anything that needs a component in the DOM should be done here.
Here is an example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
// Make a network request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
const { data } = this.state;
return (
<div>
{data ? <p>Data: {data}</p> : <p>Loading...</p>}
</div>
);
}
}
Summary
In the assembly phase, the constructor
initializes the state and binds methods. Then, componentDidMount
interacts with the DOM and makes network requests. This sequence ensures the component is ready for use and interaction.