STATE AND LIFECYCLE

State and Lifecycle

React components has a built-in state object. The state the object is where you store property values that belong to the component.

When the state object changes, the component re-renders.

Create a class component

Install a project on your laptop or You can use a https://codepen.io/

We are taking a simple example

class StateExample extends React.Component {
constructor(props) {
super(props);
this.state = {learn: "React"};
}
render() {
return (
<div>
<h1>Hello world</h1>
</div>
);
}
}

In the above code snippet, we took a class component. and Specifying the object in the constructor method :

The state object can contain as many properties as you like :

class StateExample extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: "access",
year : 2019,
};
}
render() {
return (
<div>
<h1>Hello world</h1>
</div>
);
}
}

Refer to the state object anywhere in the component by using the syntax :this.state.propertyname

Example :

Refer to the state object in the render() method :

class StateExample extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: "access",
year : 2019,
};
}
render() {
return (
<div>
<h1>name {this.state.Name}</h1>
<p>
When we started {this.state.year}
</p>
</div>
);
}
}

Changing the state Object

To change a value in the state object, use the this.setState()method.

When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).

Example :

Add a button with an onClick event that will change the color property :

class StateExample extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: "access",
year : 2019,
color: "red"
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>Name {this.state.Name}</h1>
<p>
year {this.state.year}
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
);
}
}

Lifecycle methods

Each component in React has a lifecycle that you can monitor and manipulate during its three main phases.

The three phases are: Mounting, Updating, and Unmounting.

1. Mounting

Mounting means putting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a component :

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

The render() method is required and will always be called, the others are optional and will be called if you define them.

constructor

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).

Example:

The constructor method is called, by React, every time you make a component:

class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "black"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}

render

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

class Header extends React.Component {
render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}

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.

Example :

At first, my favorite color is Black, but give me a second, and it is red instead:

class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "Black"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "red"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}

2. 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()

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 :

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

Same example as above, but this time the shouldComponentUpdate() method returns true instead :

class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "Black"};
}
shouldComponentUpdate() {
return true;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}

componentDidUpdate

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

When the component is *mounting* it is rendered with the favorite color “Black”.

When the component *has been mounted,* a timer changes the state, and the color becomes “red”.

This action triggers the *update* phase, and since this component has a componentDidUpdate method, this method is executed and writes a message in the empty DIV element:

Example:

The componentDidUpdate method is called after the update has been rendered in the DOM :

class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "Black"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "red"})
}, 1000)
}
componentDidUpdate() {
document.getElementById("mydiv").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="mydiv"></div>
</div>
);
}
}

3. 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.

Example:

Click the button to delete the header:

class Container extends React.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 React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}