reactjs
  1. reactjs-state

ReactJs State

Syntax

class ExampleComponent extends React.Component {
   constructor(props) {
      super(props);
      this.state = { 
         key1 : value1,
         key2 : value2,
         ...
         keyN : valueN
      }
   }
}

Example

Let's say we want to build a simple counter application which can increment or decrement the value of the counter. We can create a state for the component and initialize it with the initial value of the counter as shown below:

import React from 'react';

class Counter extends React.Component {
   constructor(props) {
      super(props);
      this.state = { 
         value: 0,
      };
   }
   render() {
      return (
         <div>
            <p>Current Value is: {this.state.value}</p>
            <button onClick={() => this.setState({value: this.state.value + 1})}>Increment</button>
            <button onClick={() => this.setState({value: this.state.value - 1})}>Decrement</button>
         </div>
      );
   }
}

export default Counter;

Output

The above code will produce an output like this:

Current Value is: 0
[Increment] [Decrement]

Explanation

React state is used to manage the internal state of a component. It can be used to store any type of data within the component. In the above example, we are using state to store the current value of the counter.

The state can be initialized within the constructor of the component. We can access the state data using this.state.

When the state data is modified, we should use this.setState() method to update the state. This method will automatically trigger a re-rendering of the component to reflect the new state data.

Use

There are multiple use cases of React state, some of which are listed below:

  • Storing values or data that need to be updated based on user interactions or other events
  • Controlling the behavior of the component based on certain conditions
  • Managing the internal state of complex components

Important Points

  • State should only be modified using setState() method.
  • Modifying state directly can lead to unexpected behavior.
  • State is owned by the component and can only be accessed by the component.

Summary

React state is used to manage the internal state of a component. State data can be initialized within the constructor of the component and can be accessed using this.state. State can be modified using this.setState() method. Proper use of state can help in building complex and interactive UI components.

Published on: