[go: up one dir, main page]

0% found this document useful (0 votes)
3 views8 pages

React lifecycle(1)

The React component lifecycle consists of four main phases: mounting, updating, unmounting, and error handling. Key lifecycle methods include constructor, getDerivedStateFromProps, render, componentDidMount, shouldComponentUpdate, getSnapshotBeforeUpdate, componentDidUpdate, and componentWillUnmount, each serving specific purposes during a component's lifecycle. Understanding these methods is crucial for managing state and effects in React applications.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

React lifecycle(1)

The React component lifecycle consists of four main phases: mounting, updating, unmounting, and error handling. Key lifecycle methods include constructor, getDerivedStateFromProps, render, componentDidMount, shouldComponentUpdate, getSnapshotBeforeUpdate, componentDidUpdate, and componentWillUnmount, each serving specific purposes during a component's lifecycle. Understanding these methods is crucial for managing state and effects in React applications.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

React lifecycle!

In React, components go through a lifecycle of events:


1. Mounting (adding nodes to the DOM)
2. Updating (altering existing nodes in the DOM)
3. Unmounting (removing nodes from the DOM)
4. Error handling (verifying that your code works and is bug-free)
You can think of these events as a component’s birth, growth, and death,
respectively.

Let’s look at a simple example. If I told you to build a Hello World component,
you might write something like this:
import React, { Component } from 'react'
export default class App extends Component {
render() {
return (
<div>
<h1>HelloWorld</h1>
</div>
)
}
}

The constructor() method is called before anything else, when the component
is initiated, and it is the natural place to set up the initial state and other initial
values.

The constructor() method is called with the props, as arguments, and you should
always start by calling the super(props) before anything else, this will initiate the
parent's constructor method and allows the component to inherit methods from
its parent (React Component).
import React, { Component } from 'react';
export default class App extends Component {
constructor(props){
super(props);
this.state = {color: "red"};
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.color}</h1>
</div>
)
}
}
Output:

getDerivedStateFromProps
 The getDerivedStateFromProps() method is called right before rendering
the element(s) in the DOM.
 This is the natural place to set the state object based on the initial props.
 It takes state as an argument, and returns an object with changes to the
state.
The example below starts with the favorite color being "red", but the
getDerivedStateFromProps() method updates the favorite color based on the
favcol attribute:

import React, { Component } from 'react';


export default class App extends Component {
constructor(props){
super(props);
this.state = {color: "red"};
}
static getDerivedStateFromProps(props, state) {
return {color: props.favcol };
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.color}</h1>
</div>
)
}
}
This example is contrived and not really representative of the way you’d use the
static getDerivedStateFromProps method. But I think it’s helpful for
understanding the basics.
With this lifecycle method, just because you can update state doesn’t mean you
should. There are specific use cases for the static getDerivedStateFromProps
method. If you use it in the wrong context, you’ll be solving a problem with the
wrong tool.
So when should you use the static getDerivedStateFromProps lifecycle method?
The method name getDerivedStateFromProps comprises five words: get derived
state from props. Essentially, static getDerivedStateFromProps allows a
component to update its internal state in response to a change in props.

render()
After the static getDerivedStateFromProps method is called, the next lifecycle
method in line is the render method:

The render() method is required, and is the method that actually outputs
the HTML to the DOM.

componentDidMount
The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already
placed in the DOM.

Updating
The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the


component's state or props.

React has five built-in methods that gets called, in this order, when a
component is updated:

1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()

The render() method is required and will always be called, the others are
optional and will be called if you define them.
getDerivedStateFromProps
Also at updates the getDerivedStateFromProps method is called. This is
the first method that is called when a component gets updated.

This is still the natural place to set the state object based on the initial
props.

The example below has a button that changes the favorite color to blue, but
since the getDerivedStateFromProps() method is called, which updates
the state with the color from the favcol attribute, the favorite color is still
rendered as yellow:

import React, { Component } from 'react';


export default class App extends Component {
constructor(props){
super(props);
this.state = {color: "red"};
}
static getDerivedStateFromProps(props, state) {
return {color: props.favcol };
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.color}</h1>
<button type="button" onClick={this.changeColor}>Change
color</button>
</div>
)
}
}

shouldComponentUpdate
In the shouldComponentUpdate() method you can return a Boolean value that
specifies whether React should continue with the rendering or not.

The default value is true.


The example below shows what happens when
the shouldComponentUpdate() method returns false:

import React, { Component } from 'react';


export default class App extends Component {
constructor(props){
super(props);
this.state = {color: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.color}</h1>
<button type="button" onClick={this.changeColor}>Change
color</button>
</div>
)
}
}

render
The render() method is of course called when a component gets updated, it
has to re-render the HTML to the DOM, with the new changes.

The example below has a button that changes the favorite color to blue:

import React, { Component } from 'react';


export default class App extends Component {
constructor(props){
super(props);
this.state = {color: "red"};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.color}</h1>
<button type="button" onClick={this.changeColor}>Change
color</button>
</div>
)
}
}

getSnapshotBeforeUpdate
In the getSnapshotBeforeUpdate() method you have access to
the props and state before the update, meaning that even after the update,
you can check what the values were before the update.

If the getSnapshotBeforeUpdate() method is present, you should also include


the componentDidUpdate() method, otherwise you will get an error.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and
after one second, the favorite color becomes "yellow".

This action triggers the update phase, and since this component has
a getSnapshotBeforeUpdate() method, this method is executed, and writes a
message to the empty DIV1 element.

Then the componentDidUpdate() method is executed and writes a message in


the empty DIV2 element:

import React, { Component } from 'react';


export default class App extends Component {
constructor(props){
super(props);
this.state = {color: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({color: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.color;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.color;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.color}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
)
}
}

componentDidUpdate
The componentDidUpdate method is called after the component is updated in
the DOM.

Unmounting
The next phase in the lifecycle is when a component is removed from the
DOM, or unmounting as React likes to call it.

React has only one built-in method that gets called when a component is
unmounted:

 componentWillUnmount()

componentWillUnmount
The componentWillUnmount method is called when the component is about
to be removed from the DOM.

import React, { Component } from 'react';


export default class App extends Component {
constructor(props){
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete
Header</button>
</div>
)
}
}
class Child extends Component{
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}

You might also like