State in React JS

Today we are going to explain to you what is State in React JS. Why we should use state in React Component. We will explain you the state with the help of React example.

Understanding ReactJs State, ReactJS State, What is state in React, React State with Example, How to update state in React, React state management, React get state value, initialize state in react.

State in React JS

  1. What is State and why we need State?
  2. Example

1. What is State and why we need State?

The State is plain javascript object. It is an observable variable that helps us to control the behaviour of the react components.

In other words, the State of a component is an object that holds some information that may change over the lifetime of the react component and the information can be in type of string, object, array, etc.

If you change the state value then render() method will be called automatically and UI will reflected at client side. So we can change the layout of HTML based on the value of state change.

Use below method to change the value of state in react. You can also use below method

setState” is the asynchronous method so please be careful during the updation of state. Later, we will explain you in deep in separate post.

Read more about Component State in React JS

2. Example

In this example we will show you increment and decrease number on button click. For that we will use one label to show the number and two button for increment and decrease number.

We have divided this example in three parts.

Initialize the state

First, Create component in React Application. Please refere links for create react application and then create component.

If you want to use state variable in application then first initialize it in the constructor with the help of this.state. Over here we define counter variable for display count on screen.

Write increment & decrement functions

We are going to write the functions to handle the increment and decrement of counter variable.

Passing methods to buttons

Now we assign the created method in buttons and display counter in label.

That’s it only for state in react.

Now our components should look like below.

Demo & Source Code

Github Repository

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *