In this lesson, we are going to discuss one of the most important parts of React – State. In React, a state simply refers to the data a component maintains. And when I say maintain, I meant it can actually change its value internally.

React state and life cycle methods

The state is different from props in the sense that props is a way to pass data from one component to another. It cannot be changed by the component receiving the props.

According to the React documentation, props are immutable which means you can’t change the value of props.
So, if you need data to be maintained and changed, you need to use state.

Another difference between props and state is that the concept of state is limited to class components and can’t be used within functional components.

Tip: If you need to introduce state to a component, it needs to be the class-based component and not the functional component.

So let’s understand the state with an example. As usual, start with importing React and ReactDOM.

import React from 'react'
import ReactDOM from 'react-dom'

The basic structure of the component will be:

class App extends React.component
 {

render(){
  }
 }

ReactDOM.render(<App/>, document.getElementById('root'))

Now, add some JSX in the render() method.

render(){
return 
<div>
<h1> Hello world</h1>
</div>
)
}

So far, this is what we have seen before.

To add state in this component, you need to add a constructor method which will initialize the state of the component when class is created.

To create a constructor, use constructor() method from the JavaScript ES6 and call super() method inside.

constructor(){

super()
}

super() method will inherit all the methods of React.Component class being extended.

Now, comes the state.

In react, a state is basically an object. So we will need to declare it first.

this.state = { }

Now, putting everything back to the example, we will have the following piece of code.

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
    constructor() {
        super()
        this.state = {
            name: "John"
        }
    }
    render() {
        return ( 
            <div>
            <h1> {
                this.state.name
            }
            says, Hello world </h1> 
            </div>
        )
    }
}

ReactDOM.render( < App / > , document.getElementById('root'))

This will print “John says, Hello world”.

React State Example


Stateful vs. Stateless component’s data flow

In React, parent or child component has no way to know if the certain component is stateful or stateless. No other component can access a state of the component except the one that owns it. If a component has to pass its state down to its child component, it will pass state as props.

For example.

function displayName(props){
return <h1> This is me, {props.name}</h1>
}

<displayName name={this.state.name}/>

Adding Lifecycle methods

In the example given above, we created a simple class-based component that prints something on the screen. But this isn’t as simple as it looks. The component had gone through a couple of phases to accomplish this output. These phases are referred to as the life cycle of the component.

In React 16+, the component has 3 phases: Mounting, Updating, and Unmounting.

  – Mounting is the phase when an instance of the component is created and inserted into the DOM. The first method to be called here is the constructor() method.

  – Updating is the phase when the state of the component is changed within or via API. The component has to re-rendered with the new state.

  – Unmounting is the phase when the component is removed from the DOM.

Lifecycle methods are special methods that we can declare to execute some code when a component mounts and unmounts.

Tip: A React component may or may not go through all of these phases. It may mount and unmounts without any update.

The following code is an example of a component’s structure that goes through these phases and uses lifecycle methods.

class ClassName extends React.Component {

        constructor(props) {
            super(props);
            this.state = {
                var: value
            };
        }
        componentDidMount() {
            //this method is called when component has been 
            //rendered to the DOM. 
        }
        componentWillMount() {
            //this method is called when component 
            //is removed from the DOM
        }
        render() {

            return (
                //JSX and JavaScript code goes here. 
            )
        }

Example of life cycle methods in React

Let’s understand life cycle methods with examples.

Example # 1

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
    constructor() {
        super()
        this.state = {
            name: "John"
        }
    }
    componentDidMount() {
        console.log('component did mount')
    }
    componentWillUnmount() {
        console.log('component will unmount')
    }
    render() {
        return ( <div>
            <h1> {
                this.state.name
            }
            says, Hello world </h1> {
                console.log('component created')
            }

            </div>
        )
    }
}

ReactDOM.render( < App / > , document.getElementById('root'))

Example # 2

Clock.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class Clock extends Component {
    constructor(props) {
        super(props);
        this.state = {
            date: new Date()
        };
    }

    componentDidMount() {
        console.log('Component did mount at ' + this.state.date.toLocaleTimeString())
        this.timerID = setInterval(
            () => this.tick(),
            this.props.timer
        );

    }

    componentWillUnmount() {
        clearInterval(this.props.timer);
    }

    tick() {
        this.setState({
            date: new Date()
        });

    }

    render() {
        return ( < div >
            <h1> Hello, world! </h1> 
                <h2 > It is {
                this.state.date.toLocaleTimeString()
            }. < /h2> <
            /div>
        );
    }

}
export default Clock

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import Clock from './components/Clock'

class App extends React.Component {
    render() {
        return ( <div>
            <
            Clock timer = {
                1000
            }/> <Clock timer = {
                2000
            }
            /> </div>
        )
    }
}
ReactDOM.render( < App / > , document.getElementById('root'))

Now, let’s review what’s going on here and in which order.

  1. When <App/> is called in ReactDOM.render() method, React render the <App> component, which calls <Clock/> component twice with two different props.
  2. The constructor method of <Clock/> initializes the state of the component according to the current date. this.state = {date: new Date()};
  3. React then calls the render() method of <clock/> component and displays whatever it should display on the screen by updating the DOM.
  4. When the <Clock/> is inserted into the DOM, React calls the componentDidMount() method. Inside it, it tells the web browser to call the tick() method every second.
  5. For every setState() call, React updates the DOM. One thing you need to know that this.state.var ="value" won’t re-ender a component.
    Instead, use this.state({ var: "value" }). You can use this.state in constructor only.
  6. If the <Clock/> component is ever removed from the DOM, React will call the componetWilUnmount() method.

It will take some practice for you to get used to lifecycle methods.

React Validate Props Tutorial Home React Events Handling

 

Last modified: August 22, 2019

Comments

Write a Reply or Comment

Your email address will not be published.