ScanSkill

State

A state in React is an object where we can store and modify the data of a component. In React, a class component has its own class while the state in a functional component can be achieved using react hooks.

Syntax

In a class component:

A class component has a built-in state.

Class MyClass extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = { attribute : "value" };
    }
}

In a functional component:

In functional component, useState hooks is used to maintain the state in a component.

function MyComponent(){
    const [state , setState] = useState();
}

Example

Class Component

import React from "react";


class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "John",
      grade: "3.0"
    };
  }
  render() {
    return (
      <div>
        <h2>Class Component</h2>
        {this.state.name}'s score is {this.state.grade}
      </div>
    );
  }
}

export default Test;
state

Functional Component:

import React , {useState} from "react";

function Test(){
  const [name , setName] = useState("John");
  const [grade , setGrade] = useState("3.0")
  return(
    <div>
      <h2>Functional Component</h2>
      {name}'s grade is {grade}
    </div>
  )
}

export default Test