webbuild infotech

react-state

What is State in React Js

React components has a built-in state object. The state object is where you store property values that belong to the component. When the state object changes, the component re-renders.

A state is a JavaScript object that stores a component’s dynamic data and determines the component’s behavior. Because the state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive.

Components defined as classes have some additional features. Local state is exactly that: a feature available only to classes. The state can only be used within a class and is usually the only place where you can assign this.state is the constructor.

There are Class components and Hooks so in both we can create the State in a different way.

  1. State in Class Component
  2. State in Hooks

1. State in Class Component

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);	
      this.state = {
         header: "Header from state...",
         content: "Content from state..."
      }
   }
   render() {
      return (
         <div>
            <h1>{this.state.header}</h1>
            <h2>{this.state.content}</h2>
         </div>
      );
   }
}

export default App;

main.js

import React from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);	
      this.state = {
         header: "Header from state...",
         content: "Content from state..."
      }
   }
   render() {
      return (
         <div>
            <h1>{this.state.header}</h1>
            <h2>{this.state.content}</h2>
         </div>
      );
   }
}
export default App;

2. State in Hooks

Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class.

import React, { useState } from 'react';

function StateInHooks {
 const [header, setHeader] = useState('Header');
 const [content, setContent] = useState('Content');

 return (
   <div>
       <p>This is the {header}</p>
       <p>This is the {content}</p>
       <button onClick={() => setHeader('Clicked on Button')}>
          Click me
        </button>
    </div>
 );
}

There are three things you should know about setState().

  1. Do Not Modify State Directly
  2. State Updates May Be Asynchronous
  3. State Updates are Merged

Leave a Comment

Your email address will not be published. Required fields are marked *