Understanding React State and setState

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

The state is the place where we store the data. React components have state built-in. All the property values that a component has, is stored in the state. When a state object changes, the component is re-rendered.

Creating State in React

The state is defined inside React.Component. Below code is an example of a stateful component in React.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      header: "Pratik",
    };
  }

  changeHeader = () => {
    this.setState({header: 'Pratik Sah'});
  }

  render() {
    return (
      <div>
        <h1>{this.state.header}</h1>
        <button onClick={this.changeHeader}>Change</button>
      </div>
    );
  }
}

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

Once the class extends Component, we need to call the super(); method inside the constructor. This helps us to call the parent's constructor.

this.state

Now we can use the state property to store our app's current state.

For example, here I tried to store header as "Pratik"

this.state = {
  "header": "Pratik",
}

and in my <h1></h1> tag, I've used is to display my name.

this.state.header inside h1 tag is going to return the value of header as 'Pratik'.

After that, I've created a button to manipulate the value of the state.

On clicking the button, a function named changeHeader will be called and this will change the value inside the state with the help of setState() method. The setState method is also defined inside React.Component.

Inside the changeHeader method:

changeHeader = () => {
  this.setState({header: 'Pratik Sah'});
}

Now this will change the state from 'Pratik' to 'Pratik Sah' on button click.

This is how a React state works. I hope you've understood the concept of state and setState and if you have found this post helpful, please share it with your friends.

If you stuck in any kind of error, feel free to comment your doubts in the comment section below.

If you liked this post please mark this post as Recommend by clicking the ❤️ button below in the comments section. This will help me a lot.

Thanks for your time. See you in my next post. Take care and happy coding✌️.

No Comments Yet