DEV Community

Mubasshir Ahmed
Mubasshir Ahmed

Posted on

2 2

state in react

Suppose, you don't have a girlfriend or boyfriend. So you don't have any opportunity to send a love letter. In this situation, you can create a love letter for yourself and modify it later. When you modify your own love letter that is written for yourself, it will not affect anything. Now we can start with the state object. state is a built-in object in React. It allows the component to create and manage their own data same as your love letter for yourself. The state doesn't allow passing data from one component to another. Why do you need to pass your love letter when you are single? - You can manage and create data internally. Let's build a counter using state.

import React from 'react'
class Test extends React.Component {    
  constructor(props){
    super(props)
    this.state = {
      count:0
    }
  }
  increment(){
    this.setState({
      count:this.state.count+1
    })
  }

  render() {    
      return (      
          <div>      
            <p>{this.state.count}</p>  
            <button onClick={()=>{this.increment()}}>increment</button>
          </div>    
      );  
  }
}
export default Test ;
Enter fullscreen mode Exit fullscreen mode

when you click the increment button, the state will increase.

output :Alt Text

btw change on state happens based on user input. when React gets informed about the change it immediately re-render the DOM. But it's re-render only responsible components with the updated value. It makes react faster. Once upon a time state was only used for class components. But after introducing React Hooks state can be used in class and functional components.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post