skip to Main Content

recently i came around this problem statement, where i needed to tell the value that will be printed on the button for the below react code.

    export function App() {
      const [count1, setCount1] = useState(1);
      const [count2, setCount2] = useState(count1 + 1);

      console.log('count1  :', count1);
      console.log('count2  :', count2);
      
      useEffect(() => {
        setCount2((prev) => prev + count1);
      }, [count1])
      
      return (
        <button onClick={() => {
          setCount1(count2 + 1)
        }}>
          {count2 / count1}
        </button>
      );
    }

my initial guess was that the value of count2 will be 2 and the value printed on the button will be 2/1 > 2. But on running it locally, i got to know that the answer was 4.
can someone explain to me why the value of count2 becomes 4?

2

Answers


  1. The hook useEffect is called 2 times in React Strict mode. The initial value for count2 is 2 and when useEffect is called twice, you can see that count2 is 4.

    Login or Signup to reply.
  2. Running in non-strict mode:

    • Initial render: count1 = 1; count2 = 2
    • The useEffect is triggered: count1 = 1; count2 = 3

    So, the label initially shown in the button will be 3.

    If you now click on the button:

    • count1 = 4; count2 = 3
    • the useEffect is triggered: count1 = 4; count2 = 7.

    The button will show 1.75.

    Running in strict mode:

    • Initial render: count1 = 1; count2 = 2
    • The useEffect is triggered: count1 = 1; count2 = 3
    • The useEffect is triggered again: count1 = 1; count2 = 4

    So, in this case the label of the button will be 4.

    If you now click on the button:

    • count1 = 5; count2 = 4
    • the useEffect is triggered: count1 = 5; count2 = 9
    • the useEffect is triggered again: count1 = 5; count2 = 14.

    The button will show 2.8.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search