Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now

React Component Life Cycle

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:01:00

constructor

The constructor method is used for initializing state and setting up initial values before the component is rendered.

Example

class MyComponent extends React.Component {
 constructor(props) {
  super(props);
  this.state = { count: 0 };
 }
}

getDerivedStateFromProps

This method is invoked when the component is initially created and when it receives new props. It is used to update the state based on the incoming props.

Example

static getDerivedStateFromProps(nextProps, prevState) {
 if (nextProps.value !== prevState.value) {
  return { value: nextProps.value };
 }
 return null;
}

render

The render method returns the JSX representation of the component's UI.

Example

render() {
 return <div>{this.state.count}</div>;
}

componentDidMount

This method is called after the component has been rendered to the DOM. It is commonly used for tasks like data fetching or setting up event listeners.

Example

componentDidMount() {
 // Fetch data or set up event listeners here
}

shouldComponentUpdate

This method determines whether the component should re-render after receiving new props or state. It can be used to optimize rendering by preventing unnecessary updates.

Example

shouldComponentUpdate(nextProps, nextState) {
 return nextProps.id !== this.props.id;
}

getSnapshotBeforeUpdate

This method is called right before the component's DOM is updated. It allows you to capture some information from the current DOM for use in componentDidUpdate.

Example

getSnapshotBeforeUpdate(prevProps, prevState) {
 if (prevProps.value !== this.props.value) {
  return 'Value changed';
 }
 return null;
}

componentDidUpdate

This method is called after the component has been updated and re-rendered. It is often used for performing actions that depend on the updated state or props.

Example

componentDidUpdate(prevProps, prevState, snapshot) {
 if (snapshot === 'Value changed') {
  // Handle the value change
 }
}

componentWillUnmount

This method is called just before the component is removed from the DOM. It is used for cleanup tasks like removing event listeners or timers.

Example

componentWillUnmount() {
 // Clean up resources here
}
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this