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 !
iand the functions that capture it are remade every render. It needs to also useuseState.