Site icon Learn Web Development & Programming, Artificial Intelligence, WordPress, Shopify Articles

State in React Component

State is similar to props, but it is private and fully controlled by the component. We can create state only in class components. It is possible to update the state/Modify the state. In this article, we will discuss about State in React Component. I will show you two way to initialize state in React Component:-

1. Directly inside class

In Directly inside class, we can write a class component without a constructor. If we write state without constructor then it will work as property. Let me explain through an example:-

In the above example, I declare an Employee class component with State. Here State is a class property. You can see, I am getting state value using this.state which is the correct way to access class property details.

Note:-

Inside the Constructor

When the component class is created, the constructor is the first method called, so it’s the right place to add a state. When we create a constructor, It is required to call the parent class constructor. To call parent class constructor you need to define super(props) function or method. When you call super with props. React will make props available across the component through this.props. The class instance has already been created in memory, so you can use “this” to set properties on it.

Example:

In the above example, I created a class component with a constructor. To call parent class constructor you can see, super(props) function or method is defined.

Props in ReactJS

What is JSX in React?

Exit mobile version