React JS State

State is a JavaScript object that stores a component's dynamic data and determines the component's behavior. Because state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive. State can only be used within a class component.

We can get more ideas by looking at the below example. you can put this file in /src/components folder and put in /src/App.js file.

Component

Example
import React, { Component } from 'react'; class ReactTutorialState extends Component { constructor(){ super() this.state = { message: 'Hello Ramesh' } } render() { return( <div> {console.log(this.state)} {this.state.message} </div> ); } } export default ReactTutorialState;

When we run above code, It will show console log as Object > {message : 'Hello Ramesh' } and browser shows Hello Ramesh.

Let's discuss in more detail,

Example
class ReactTutorialState extends Component { constructor(){ super() this.state = { message: 'Hello Ramesh' } } changeMessage() { this.setState({ message: 'Button clicked!!!'}); } render() { return( <div> <h1> {this.state.message} </h1> <button onClick={() => this.changeMessage()}>Change Message</button> </div> ); } }

In above code, we use one button and on click (we understand eventHandler of element in details in next tutorial) of that button message will change with the use of state. here, we created a function changeMessage(), when user click on button our message state is updated from 'Hello Ramesh' to 'Button clicked!!!'. In functional component it worked as different way.

Difference between Props and States

Props

  • 1. props get passed to component
  • 2. functions parameters
  • 3. props are immutable - props can't change in child component
  • 4. props - Functional components, this.props - Class component

State

  • 1. state managed within the component
  • 2. variable declare within a functional body
  • 3. state can be changed
  • 4. useState Hook - Functional components, this.state - Class component

 

← Previous

Next →