MORE ABOUT STATES

 THE COMPONENT IS RENDERED ONLY IF THERE IS A CHANGE IN STATE VARIABLE OR VALUE.

import { useState } from "react";

export default function Counter() {
  let [count, setCount] = useState(0);
  console.log("component is rendered!");
  console.log(`count=${count}`);
  let incCount = () => {
    setCount((currCount) => {
      return currCount + 1;
    });
   
  };
  return (
    <>
      <h3>Count={count}</h3>
      <button onClick={incCount}>increase count</button>
    </>
  );
}


HERE AS THE COUNT VARIABLE CHANGES EVERYTIME THE BUTTON IS CLICKED, THE PAGE RE-RENDERS.

IF THERE IS NO CHANGE IN THE STATE VARIABLE , IT DOES'NOT RE-RENDER.

    setCount(25);

HERE THE COUNT VARIABLE IS NOT UPDATED , HENCE IT IS NOT RENDERED AFTER TWO CLICKS.


WHEN init() IS USED FOR INITIALIZATION.

function init() {
  console.log("init is initialized!")
  return Math.random();
}
export default function Counter() {
  let [count, setCount] = useState(init());
  console.log("component is rendered!");


THE INITIAL VALUE IS RE-INTIALIZED EVERYTIME .

HENCE WE USE ONLY init.

  let [count, setCount] = useState(init);

HERE INITIALIZED IS ONLY DONE ONCE.








Comments

Popular posts from this blog

DEPENDENCIES IN useEffect()

ACTIVITY1

CONDITIONALS