Saturday, April 23, 2022

ReactJS Part 5 State

State are used for changing values within a React Component. 

useState is required to implement State in React functional component. It returns a variable and a function. I am using ES6 array destructing to hold the variable and function. 

 


import React, { useState } from 'react';

function useStateHookDemo(props) {
  let [numberOfClicks, setNumberOfClicks] = useState(123);

  return (
    <div>
      <h1>Number of clicks is {numberOfClicks}</h1>
      <button onClick={() => setNumberOfClicks(numberOfClicks + 1)}>
        Counter
      </button>
    </div>
  );
}

export default useStateHookDemo;

In the button click the function to alter the state variable is called.

No comments:

Post a Comment