How to manage state in React?

How to manage state in React?

·

2 min read


I'm sure you're thinking about application state while you make a plan for your app. You're trying to figure out how you should use React's default features. In this post we will discuss about the basics of set state for class components. Let's go.


What is a state?

The state of a component is an object that holds information that may change over the lifetime of the component. The state is used to track form inputs, capture dynamic data from an API, etc.

Example of creating a Local State

class User extends React.component {
   constructor(props) {
      super(props); 
      this.state = { name: 'Rahul'}; 
    }
  }

Assign initial state inside the class constructor.


Read state values

console.log(this.state.name); 

// Output : Rahul

Update state values

// Wrong way
this.state.name = 'Rahul'; 

// Correct way
this.setState({name : 'Rahuk'}); 
console.log(this.state.name); 
// Output : Rahul

State update values may be asynchronous and are merged.

// count : 0
this.setState({count:count + 1}); 
//count : 1
this.setState({count:count + 1}); 
// count : 1

Here, both the setState count is enqueued when the value of count is 0.

So basically when passing a function of setState that takes the previous state and updates the state in a synchronous manner.

//count : 0
this.setState((prevState)=>{
    return {count : prevState.count + 1}
  }); 
// count : 1  

this.setState((prevState)=> {
   return {count : prevState.count + 1}
 }); 
 //count : 2

Orginally => https://rahulism.tech/article/how-to-maintain-states-in-react/


😴Thanks For Reading | Happy Reacting😀

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!