Mastering React Component Lifecycle: The Foundation for React Concepts
Tags: react, javascript, webdev, reactnative
Published: 2024-06-03 16:52:06

React, with its component-based architecture and declarative syntax, has become a staple in modern web development. However, to truly harness the power of React, understanding its lifecycle methods is essential. These methods form the foundation for advanced concepts like re-rendering, caching, and performance optimisation. In this blog, we'll take a comprehensive look at React's lifecycle methods, diving deep into each phase and providing practical examples along the way.

Intro to React and its Component Lifecycle
React's lifecycle can be divided into three main phases: Mounting, Updating, and Unmounting. Each phase has specific methods that allow developers to hook into the component's lifecycle and execute code at precise moments. Let's explore these phases and methods in detail.

1. Mounting Phase
The Mounting phase occurs when a component is first created and inserted into the DOM. Here are the key methods in this phase:

1.1 constructor(props)
The constructor method is where you initialize state and bind event handlers. It's called before the component is mounted.

for example :- 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xp5gdfgg8ue3uw2kw6ze.png)

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>
    );
  }
}


1.2 static getDerivedStateFromProps(props, state)
The getDerivedStateFromProps method is called before rendering the component, both during the initial mount and subsequent updates. It should return an object to update the state, or null to update nothing.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxs8708mpauigjrf76vj.png)

class MyComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.someValue !== prevState.someValue) {
      return { someValue: nextProps.someValue };
    }
    return null;
  }
}


1.3 render()
The render method is required and returns the JSX that makes up the component's UI.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jid3puqprc18xwgebq1b.png)

render() {
  return (
    <div>
      <p>Count: {this.state.count}</p>
      <button onClick={this.handleClick}>Increment</button>
    </div>
  );
}

1.4 componentDidMount()
The componentDidMount method is invoked immediately after a component is mounted. It's a good place to fetch data from an API or set up subscriptions.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mqaivjjdt4q4v9mqnf5s.png)

componentDidMount() {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => this.setState({ data }));
}


2. Updating Phase
The Updating phase occurs when a component's state or props change. Here are the key methods in this phase:



2.1 static getDerivedStateFromProps(props, state)
The getDerivedStateFromProps method is called again in this phase, allowing the component to update its state in response to prop changes.



2.2 shouldComponentUpdate(nextProps, nextState)
The shouldComponentUpdate method determines whether the component should update. By default, it returns true. Returning false can prevent unnecessary updates, improving performance.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mi9n4f0ee6wq6eiq3rgt.png)

shouldComponentUpdate(nextProps, nextState) {
  return nextState.count !== this.state.count;
}

2.3 render()
The render method is called again to re-render the component with the new state or props.

2.4 getSnapshotBeforeUpdate(prevProps, prevState)
The getSnapshotBeforeUpdate method is called just before the changes from the virtual DOM are applied to the DOM. It captures some information (e.g., scroll position) from the DOM before it is potentially changed.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/475vq6yefffnjj63aa1i.png)

getSnapshotBeforeUpdate(prevProps, prevState) {
  if (prevState.list.length < this.state.list.length) {
    const list = document.querySelector('ul');
    return list.scrollHeight - list.scrollTop;
  }
  return null;
}

2.5 componentDidUpdate(prevProps, prevState, snapshot)
The componentDidUpdate method is called after the updates are applied to the DOM. It's a good place to perform network requests or DOM manipulations that depend on the component being updated.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7m5vowegnhedc7i5tr8.png)

componentDidUpdate(prevProps, prevState, snapshot) {
  if (snapshot !== null) {
    const list = document.querySelector('ul');
    list.scrollTop = list.scrollHeight - snapshot;
  }
}

3. Unmounting Phase
The Unmounting phase occurs when a component is removed from the DOM. Here's the key method in this phase:

3.1 componentWillUnmount()
The componentWillUnmount method is called just before a component is unmounted. It's used to clean up resources like event listeners or timers to prevent memory leaks.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkat6lamwskmikzpt8mm.png)

componentWillUnmount() {
  // Clean up resources here
}

Error Handling Phase
React also provides methods for error handling during rendering and lifecycle methods:

4.1 static getDerivedStateFromError(error)
The getDerivedStateFromError method is called when a descendant component throws an error. It allows the component to update its state to render an error message.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkb79mljo1h7cwlh8ufs.png)

static getDerivedStateFromError(error) {
  return { hasError: true };
}

4.2 componentDidCatch(error, info)
The componentDidCatch method is called after a component catches an error in its descendants. It's used for logging errors or displaying a fallback UI.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zyho9uym6v1yv8kjo6dg.png)

componentDidCatch(error, info) {
  logErrorToService(error, info);
}


Deprecated Methods
Some methods were used in older versions of React but have been deprecated. These include:

UNSAFE_componentWillMount()
UNSAFE_componentWillReceiveProps(nextProps)
UNSAFE_componentWillUpdate(nextProps, nextState)
These methods are no longer recommended and should be avoided in new code.

Conclusion: Why Mastering Lifecycle Methods Matters
Understanding React's component lifecycle methods is crucial for efficient and robust application development. These methods give you control over component behaviour, optimise rendering performance, manage resources effectively, and handle errors gracefully.

By mastering these basics, you pave the way for advanced React concepts like re-rendering, caching, and performance optimisation. So dive deep into React's lifecycle methods, experiment with them, and elevate your React development skills to the next level!