React States

In React, state is the object where the component properties can be stored. It is an updatable structure which contains data or information related to the component. Whenever the property value in a state changes, the component gets re-rendered.


state Object


The state object is always initialied inside the constructor() function. Here's an example on how the state can be initalized:


import React from 'react'

class FirstComponent extends React.Component {
  constructor(){
    super();
    this.state = {
      name: "John Doe"
    }

  }

  render(){
    return (
    <h3>Dealing with states </h3>

    )
  }
}


There's no restriction on how many number of properties a state can have:


import React from 'react'

class FirstComponent extends React.Component {
  constructor(){
    super();
    this.state = {
      name: "John Doe",
      city: "Venice",
      age: 30,
      jobtitle: "BusinessMan"
    }
  }

  render(){
    return (
    <h3>Dealing with states </h3>
    )
  }
}


Rendering the state object

As state is an object, all its properties can be accessed using the . dot notation. The syntax will be this.state.propertyName inside {} curly brackets.


import React from 'react'

class FirstComponent extends React.Component {
  constructor(){
    super();
    this.state = {
      name: "John Doe",
      city: "Venice",
      age: 30,
      jobtitle: "Project Manager"
    }
  }

  render(){
    return (
    <h1>{{this.state.name}} lives in {{this.state.city}},
    age is {{this.state.city}} and job is {{this.state.jobtitle}} </h1>
    )
  }
}


This is how the output will look like:


Modifying the state object


state object can be modified using the this.setState() method. So whenever the state object value is updated using the this.setState() method, the component is re-rendered.


  import React from 'react'

  class FirstComponent extends React.Component {
    constructor(){
      super();
      this.state = {
        name: "John Doe",
        city: "Venice",
        age: 30,
        jobtitle: "Project Manager"
      }
      //Remember that we need to bind 'this' with the function
      this.clickHandler = this.clickHandler.bind(this)
    }

    clickHandler(){
      //On clicking the button, the city will change
      this.setState({
        city: "New York"
      })
    }

    render(){
      return (
      <h1>{{this.state.name}} lives in {{this.state.city}},
      age is {{this.state.city}} and job is {{this.state.jobtitle}} </h1>
      <button onClick={this.clickHandler}>Click Me</button>
      ) 
    }
  }


Remember that we need to bind the this keyword with the clickHandler() function because it is not defined inside the clickHandler() function. So in order to define it and make it usable, we need to bind it.