Thursday 31 May 2018

- Like all living things even React Component  has a lifecycle means a component takes birth, grows by updates and then dies in a web browser.

- The Component lifecycle methods are various methods which are invoked at different phases.

Four phases of a React component

• Initialization

• Mounting

• Updation

• Unmounting

1) Initialization

In this phase the React component sets the initial states and default props. For this two methods being called are -

1. getInitialState - getInitialState method enables to set the initial state value, that is accessible inside the component via this.state.

2. getDefaultProps - getDefaultProps can be used to define any default props which can be accessed via this.props.

2) Mounting

After initialization, our React Component is ready to mount in the browser DOM. The methods which gets called in this phase are -

1. componentWillMount - It is executed just before the React Component is about to mount on the DOM.

- It is called before the render method is executed.

2. componentDidMount - This is the hook method which is executed after the component did mount on the dom.

- It is called as the render method has been executed.

3) Updation

This phase starts when the react component receives new updates. The component can be updated by two ways, sending new props or updating the state.

State Changes

1. shouldComponentUpdate

- It tells the React that when the component receives new props or state is being updated, should React re-render.

- This method should return true or false.

- By default, this method return true.

2. componentWillUpdate

- It is executed only after the shouldComponentUpdate returns true.

3. componentDidUpdate - It is executed when the new updated component has been updated in the DOM.

Props Changes

Any changes on the props object will also trigger the lifecycle and is almost identical to the state change with one additional method being called componentWillReceiveProps.

1. componentWillReceiveProps - It gets executed when the props have changed and is not first render.

The rest of the methods behave exactly same -

2. shouldComponentUpdate

3. componentWillUpdate

4. componentDidUpdate

4) Unmounting

In this phase, the component is not needed and the component will get unmounted from the DOM.

1. componentWillUnmount - This method is the last method in the lifecycle. This is executed just before the component gets removed from the DOM.

No comments:

Post a Comment

Chapter : 1 - First code in Node JS Previously I have written a blog about Getting Started with Node JS and its installation. Now lets s...