Component Mounting Phase in React
Key Concepts
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
constructor()
The constructor is the first method called during the mounting phase. It is used for initializing state and binding event handlers. The constructor is called before the component is mounted to the DOM.
Example:
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; 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> ); } }
static getDerivedStateFromProps()
This static method is called right before rendering the element(s) in the DOM. It is used to update the state based on changes in props. It should return an object to update the state, or null to update nothing.
Example:
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } static getDerivedStateFromProps(props, state) { if (props.initialCount !== state.count) { return { count: props.initialCount }; } return null; } render() { return ( <div> <p>Count: {this.state.count}</p> </div> ); } }
render()
The render method is required and is responsible for describing the view to be rendered to the DOM. It returns React elements, arrays, fragments, portals, or null. The render method should be pure, meaning it does not modify component state.
Example:
class MyComponent extends React.Component { render() { return ( <div> <h1>Hello, World!</h1> </div> ); } }
componentDidMount()
This method is called immediately after a component is mounted (inserted into the tree). It is a good place to perform side effects such as fetching data, starting timers, or setting up subscriptions.
Example:
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => this.setState({ data })); } render() { return ( <div> <ul> {this.state.data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); } }
Analogies
Think of the mounting phase as building a house. The constructor is like laying the foundation, static getDerivedStateFromProps is like checking the blueprints, render is like constructing the walls, and componentDidMount is like moving in and setting up utilities.
Another analogy is a theater play. The constructor is like the actors getting into costume and makeup, static getDerivedStateFromProps is like the director reviewing the script, render is like the actors taking the stage, and componentDidMount is like the audience applauding after the curtain rises.