Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't a variable increment in my React component as expected?

I’m a React learner and I want to understand something. The code below doesn’t work, it’s just a component with two buttons that add or substract a number and display it. Here’s the whole code :

import React from "react";
import { useState } from "react";

const Compteur = () => {
  let i = 0;
  const [number, setNumber] = useState(0);

  const increment = () => {
    i++;
    setNumber(i);
  };

  const decrement = () => {
    i--;
    setNumber(i);
  };

  return (
    <div>
      <button type="button" onClick={increment}>
        +
      </button>
      <button type="button" onClick={decrement}>
        -
      </button>
      <p>Number : {number}</p>
    </div>
  );
};

export default Compteur;

But if I replace setNumber(i) by setNumber(number + 1), it works well. What’s the problem with this i variable ? Thanks for your help !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Welcome to React!

The problem in your example is that each time the component rerenders (in your case due to a state change), i is reinitialized and assigned a value of 0. I think you’re thinking of the component more as a loop, versus a javascript file. React does a great job as maintaining state, and that state will stay the same though rerenders of the component, which is why it’s working as expected when you use number (a piece of React state) instead of i

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading