useState hook in React

useState hook is used to store the state of component. Everytime you change the state, component will re-render and UI will get updated. If you do not want the component to re-render, you can use useRef hook instead. In below example, we have created a timer which will start running as soon as component is rendered. Component will re-render after every 1 second and show updated count(state). a ZZZ A2Q3

import { useEffect, useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);

  function incrementCounter() {
    setCount((prev) => {
      return ++prev;
    });
  }

  useEffect(() => {
    setTimeout(incrementCounter, 1000);
  });

  return <span>counter {count}</span>;
}

export default Counter;

Web development and Automation testing

solutions delivered!!