DEV Community

Cover image for How to manage state in React?
Rahul
Rahul

Posted on

How to manage state in React?

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'}; 
    }
  }
Enter fullscreen mode Exit fullscreen mode

Assign initial state inside the class constructor.


Read state values

console.log(this.state.name); 

// Output : Rahul
Enter fullscreen mode Exit fullscreen mode

Update state values

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

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

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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


😴Thanks For Reading | Happy Reacting😀



Top comments (0)