Sobes.tech
Junior — Senior

Finding the cause of incorrect counter increment in a React component

livecode

Task condition

Every time the first button is clicked, it is expected that the value will increase by 1, reflecting the total number of clicks. In the current implementation, the counter increases only once. It is necessary to analyze the code, find out why the state does not change with each event, and suggest a fix.

import { useCallback, useEffect, useMemo, useState } from "react";

export function App() {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState({
    name: 'Anton',
  });

  const handleBtnClick2 = () => {
    count2.name = "Alex";
    console.log(count2.name);
    setCount2(count2);
  };

  const btnClick = () => {
    setCount(count + 1);
  };

  const handleBtnClick = useCallback(() => {
    btnClick();
  }, []);

  return (
    <div>
      <button onClick={handleBtnClick}>{count}</button>
      <button onClick={handleBtnClick2}>{count2.name}</button>
      {/* <button onClick={btnClick2}>Compute Heavy</button> */}
      <div />
      <input type="text" />
    </div>
  );
}