Skip to main content

React Lifecycle

Three steps of react life cycle;

  1. Mounting - Birth of your component (comming in the App)
  2. Update - Growth of your component (changing,growth)
  3. Unmount - Death of your component
  4. Error Handling

Mounting

constructor

In the constructor, you initialize the component state and bind event handlers. It's called before the component is mounted.

constructor(props) {
super(props);
this.state = {
count: 0
};
// Binding a method to the current instance
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}

render

The render method returns the JSX (React elements) that represents the component's UI. It's mandatory and must be a pure function.

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

componentDidMount

  • Called immediately after a component is mounted. Setting state here will trigger re-rendering.
  • This method is called after the component is rendered to the DOM.
  • It's often used for making AJAX requests, setting up subscriptions, or interacting with the DOM.
componentDidMount() {
console.log('Component mounted');
// Example: Fetching data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('Received data:', data);
// Update state with fetched data
this.setState({ data });
})
.catch(error => {
console.error('Error fetching data:', error);
});
}

Updating

componentDidUpdate

  • executed after each update.
  • This method is called immediately after the component updates (re-renders).
  • It's useful for performing actions that depend on the DOM or interacting with external APIs based on new props or state.

shouldComponentUpdate

  • This method is called before the component re-renders.
  • It allows you to control if the component should update or not based on the new props or state.
  • Called to determine whether the change in props and state should trigger a re-render.
shouldComponentUpdate(nextProps, nextState) {
// Compare current props and state with nextProps and nextState
// Return true if the component should update, false otherwise
if (this.props.someProp !== nextProps.someProp || this.state.someState !== nextState.someState) {
return true;
}
return false;
}

Unmounting

componentWillUnmount

  • executed before the component is removed from the DOM.
  • Called immediately before a component is destroyed.
  • Perform any necessary cleanup in this method, such as cancelled network requests, cleanup tasks such as invalidating timers, or cleaning up any DOM elements created in componentDidMount.
componentWillUnmount() {
// Clean up any resources like timers, subscriptions, etc.
clearInterval(this.timerID);
}

This prevents memory leaks and ensures that resources are properly cleaned up when the component is removed from the DOM.

Error Handling

The fourth type of lifecycle methods are the ones that only run when something goes wrong with your component.

  1. getDerivedStateFromError()
  2. componentDidCatch()

getDerivedStateFromError

This lifecycle method receives the error that occurred and should return an object that will be used to update the state.

componentDidCatch

  • Catches exceptions generated in descendant components. Unhandled exceptions will cause the entire component tree to unmount.

Benefits

  • Prevents Crashes: Ensures that errors in one part of the UI do not affect the entire application.
  • Error Reporting: Allows for centralized error handling and reporting, improving debugging and maintenance.
  • Fallback UI: Provides a graceful user experience by showing a fallback UI instead of crashing the application.