useState

Key Points

  • useState is a react hook that returns an array
    • first parameter is the initial value
    • second parameter is the function which controls the initial value between render
  • console.log(useState()); //(2) [undefined, ƒ]
  • console.log(useState()[0]); //undefined
  •  console.log(useState()[1]);
      //     ƒ dispatchSetState(fiber, queue, action) {
      //    {
      //       if (typeof arguments[3] === ‘function’) {
  • const [randomDiceroll, SetrandomDiceroll] = useState(3);
    • initial value – randomDiceroll is 3
    • SetrandomDiceroll is a method to to control randomDiceroll
  • Hooks must be inside function or component body
  • Hooks should be in uppercase.
 
				
					import React, { useState } from "react";

const UseState = () => {
  const [randomDiceroll, SetrandomDiceroll] = useState(3);

  let changeDiceRoll = () => {
    SetrandomDiceroll(Math.floor(Math.random() * 6) + 1);
  };

  return (
    <>
      <div className="myClass">
        <p>{randomDiceroll}</p>
        <button onClick={changeDiceRoll}>ROll DICE</button>
      </div>
    </>
  );
};
export default UseState;

//align div to center

				
			

Now the value changes on click of button

Leave a Comment