Chapter 6 – React Component Lifecycle with Example

No. 1101, 24th Main, JP Nagar, 1st Phase, Bangalore 560 078
Initialization: In this phase, the component is initiated with props and default state. The general place to set the default values is a constructor. The constructor method is called only once and called before any other method.
Mounting: After the initial phase, the component is created and inserted into the DOM. It consists of the following methods.
Updating: Component is updated whenever state or props is changed.
It consists of the following methods.
Unmounting: In this phase, the component is unmounted from the DOM. It has only one lifecycle method.
Let’s change our class component as shown below.
class ClassComponentExample extends React.Component { constructor(props){ super(props); console.log('CONSTRUCTOR!') this.state = { messageB1:"Default Message B - 1", messageB2:"Default Message B - 2", } } componentWillMount() { console.log('COMPONENT WILL MOUNT!') } componentDidMount() { console.log('COMPONENT DID MOUNT!') } b1OnClick = () =>{ this.setState({ messageB1:"B-1 Button Clicked :)" }) } b2OnClick = () =>{ this.setState({ messageB2:"B-2 Button Clicked :)" }) } render() { console.log('RENDER!') return} }{this.props.message}
{this.state.messageB1}
{this.state.messageB2}
Now do npm start and check your browser console. You can see the logged messages.
As you can see the component contains lifecycle methods from initialization and mounting phase. Let’s add the updating phase and unmounting phase methods after componentDidMount() method.
componentWillReceiveProps(newProps) { console.log('COMPONENT WILL RECIEVE PROPS!') } shouldComponentUpdate(newProps, newState) { console.log('SHOULD COMPONENT UPDATE!') return true; } componentWillUpdate(nextProps, nextState) { console.log('COMPONENT WILL UPDATE!'); } componentDidUpdate(prevProps, prevState) { console.log('COMPONENT DID UPDATE!') } componentWillUnmount() { console.log('COMPONENT WILL UNMOUNT!') }
Now refresh the page, click on B1 Button and check the browser console. After clicking the B1 Button updating phase methods are invoked except componentWillReceiveProps() method since the ClassComponentExample is not receiving any new props.
Understanding the component lifecycle is important because lifecycle methods give us better control over the components. You can override any of these lifecycle methods and write your own logic.
Hey! Just wanted to say great site. Keep up the good work!