State Change in Functional Component using useState Hooks in React JS

In React, functional components can manage state using the useState hook. The useState hook allows you to declare state variables in your functional components and update them. Functional components are much more convenient than class components.

Structure Image

  • Import useState from the React package
  • Assign a variable (age) with initialize as zero using useState() method.
  • Function IncrementAge fires at the click of a button.
  • The age variable value/state changing inside IncrementAge function using setAge() method.


Code 👇
StateInFunctionalComponent.js

import React, {useState} from 'react'

function StateInFunctionalComponent() {
    const [age, setAge] = useState(0);

    const IncrementAge = () => {
        setAge(age + 1)
    }

  return (
    <div>
        <h4>Age : {age}</h4>
        <button onClick={IncrementAge}>+</button>
    </div>
  )
}

export default StateInFunctionalComponent


App.js

import React, { Component } from 'react';
import StateInFunctionalComponent from './components/StateInFunctionalComponent/StateInFunctionalComponent.js'

export default class App extends Component {
  render() {
    return (
      <div>

        <h4>State Change in Functional Component with useState hooks</h4>
        <StateInFunctionalComponent />

      </div>
    )
  }
}

Post a Comment

0 Comments