What Is 'State' in ReactJS?

A state is a component object built into React that contains data or information. Throughout the life cycle of a component, its state can change; re-rendering occurs whenever the state changes.

A change in state can occur as a result of user interaction or system events, and it determines how the component behaves and renders.

The setState() Method

Depending on the event handler, the server response, or the property change, the state can get updated. The setState() method does this.

The setState() method adds all changes relating to the component state and resets React to render the component and its children accordingly.

To change the state object of a component, use the setState() method. That way, the component will know it has changed so it will call the render() method appropriately. When updating the UI, this is the best method to use.

Syntax

setState(updater, [callback])

Parameters

updater

A function with the signature: (state, props) => stateChange.

state reflects the component's current, up-to-date state and the function returns it.

callback

Upon updating the state, you can specify a callback function.

this.setState((state, props) => {
  return {count: state.count + props.step};
});

Rules of Using setState( )

Rule 1: Try not to change state directly

As shown below, you should never directly change a state variable's value; use a function instead.

//wrong
this.state.inputValue = e.target.value;
//correct
this.setState({inputValue:e.target.value}) 

Rule 2: State Updates can be asynchronous

Always include a callback function in a state variable update that results in an asynchronous request. Below is an example of code.

changeName = async(e) => {
await this.checkAvailability(e.target.value)
};
checkAvailability = async(user_name) => {
  setTimeout(() => {
    if(user_name.includes('a')) {
      this.setState({ isAvail: true });
    }else {
      this.setState({ isAvail: false });
    }
    this.setState({ name: u_name});
    console.log(this.state.isAvail)
  }, 300);

Rule 3: Merging state updates

Perform their updates in one function instead of using multiple this.setState() calls. See the example below:

//Wrong approach
if(this.state.inputValue === ''){
   this.setSatte({name: 'John'})
   this.setSatte({age: 36})
   this.setSatte({metadata: {nationality: 'American', gender: 'male'}})
}
//right approach
if(this.state.inputValue === ''){
   this.setState(
     {
        name: 'John',
        age: 36,
        metadata: {nationality: 'American', gender: 'male'}
     }
  })
}

Code Example

The following code will help you understand how to use SetState in your react application.

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

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  // Increments the count based on props.step
  counter_incr= () => {
    this.setState((state, props) => {
      return { count: state.count + props.step };
    });
  };

  // Reset the counter back to 0
  counter_reset = () => {
    this.setState({ count: 0 });
  };

  render() {
    return (
      <div>
        <p>The count is {this.state.count}.</p>
        <button onClick={this.counter_incr}>+ {this.props.step}</button>
        <button onClick={this.counter_reset }>Reset counter</button>
      </div>
    );
  }
}

ReactDOM.render(<Counter step={1} />, document.getElementById("root"));

write your code here: Coding Playground

Use the following command in the root directory of your project to run the application:

npm start

Output

Conclusion

Almost every dynamic application involves state management. A React component can manage the state using a simple and flexible API provided by React.

React components can often change state as a result of user actions, network activity, API requests, or specific application behavior.