React.js — Manage States

Tanuka Das
2 min readNov 11, 2019

--

In React state is simply data that its component maintains, which means the component can change its value. State is a class instant property defined as an object to store data in React. It is maintained by components, whenever a component needs to be in charge of maintaining its own information (as opposed to being passed that information from a parent component via props), you’ll use state. If needed a component can make its own data and change its own data. Basically, if you need data that needs to be modified, you can keep it in state.

There are two ways to initialize state in React Component:

— Directly inside class

— Inside the constructor

State Without Constructor

Create a class component, called Employee extends the class component. Write state inside the class, without constructor, in this case, state is the property of Employee class. Initialize the state with a property called count and set that equal 0. Next, in the render method, we have an h1 tag that displays the current count, using {this.state.name}. Here, ‘this’ points to the instant, ‘state’ refers to the state and ‘name’ is the property we’re trying to access. We can access the state anywhere in this class.

State With Constructor

Add a constructor method inside class; constructor is a specific method that is built-in to javascript, that initializes parts of this class. Its a place where we initialize some values. inside the constructor, make a call to a global function called super. the super goes to the parent class or, (React.Component) also know as superclass and it grabs information from there and brings them down to our class or our app component can use that info. So, whenever we use constructor we must add ‘super’. To add state to the component, all we need is add a property to this.state; state will always be an object so set this.state equal to an object. Now it can be accessed anywhere in the class by referencing this.state. Similar to state without component, add a property to the state as an initial value.

--

--

Tanuka Das
Tanuka Das

Written by Tanuka Das

Software Developer, technical writer, bookworm, constant learner.

No responses yet