React State

The state is a region or store where all the data we want comes from. The state of any given component should be as minimal as possible. A state is a JavaScript object containing data we would like to use in our app. In our earlier example of an e-commerce website, the state of our products should be present in the <Body/> component and can then be passed down as props to its children's component.

Usage of State

A state can be created with a class component like below, a class function has a built-in state object:

Product.js:

import React from 'react'

export default class Product extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      product: "ice-cream",
    };
  }
  render() {
    return (
      <div>
        <h3> I love {this.props.product} from props </h3>
        <p> I love {this.state.product} from state</p>
      </div>
    );
  }
}

Result:

State originally belonged only to the class-based components, giving functional components the name ‘stateless components’ but that became false when Hooks were introduced in 2019.

The state of a class component can be changed only by using the function this.setState(). For example,

import React from 'react'

export default class Product extends React.Component {
   constructor() {
   super()
   this.state = {
   product: 'ice-cream'
   }
}
   changeProduct = () => {
   this.setState({
   product: 'Doughnuts'
   })
   }
   render() {
   return (
   <div>
   <p> I love {this.state.product}</p>
   <button onClick={this.changeProduct}>change product</button>
   </div>
   )  
   }
}

Result:

This can be explained thus:

The original state contained data ‘product’ with value ‘ice-cream’, when the button is clicked, the event ‘onClick’ is triggered and a function changeProduct() is activated that changes the state object’s product value to ‘Doughnut’.  Open the browser’s console and navigate to the root <div>, then check the <p> element. Click the button, notice that only ‘ice-cream’ is changed without the whole page re-rendering. That is the power of React virtual DOM.

Putting it together

Let’s create an example where we initialize a state in a Products component and render their value to the browser.

Products.js:

import React, { Component } from 'react'

export default class Products extends Component {
    state = {
        productName: 'Doughnuts',
        id: 20092,
        company: 'Doughnuts & Co.'
    }
    render() {
        return (
            <div>
              <></> 
            </div>
        )
    }
}

In Products.js, we initialized a state containing a product name, id, and the company. We now desire to render their values to the screen:

Products.js:

import React, { Component } from 'react'

export default class Products extends Component {
    state = {
        productName: 'Doughnuts',
        id: 20092,
        company: 'Doughnuts & Co.'
    }
    render() {
        return (
            <div>
                <h1>Product</h1>
               <h3>{this.state.productName}</h3>
               <p>Product ID: {this.state.id}</p>
               <p>Courtesy of <strong>{this.state.company}</strong> </p> 
            </div>
        )
    }
}

We refer to the state by using the ‘this’ keyword to indicate the current class followed by the property name, this.state.propertyName.

Result:

React gives us the opportunity to think more, so as to write less.