I'm trying to create a simple recursive function that adds random numbers to an array until the sum of that array is 10.
function App() {
const [array, setArray] = useState([1, 2, 3]);
const [sum, setSum] = useState(0);
const getRandNum = () => {
const num = Math.floor(Math.random() * 5);
setArray((prev) => [...prev, num]);
};
useEffect(() => {
setSum(() => {
return array.reduce(
(acumulator, currentValue) => acumulator + currentValue,
0
);
});
}, [array]);
const func = () => {
if (sum >= 10) return;
setTimeout(() => {
getRandNum();
func();
}, 500);
};
return (
<>
<div className="App">
{array.map((num) => (
<p>{num}</p>
))}
</div>
<button onClick={() => func()}>click</button>
<p>sum: {sum}</p>
</>
);
}
This recursive function func()
does not stop calling itself. It keeps adding numbers even though sum
is greater than 10.
I know what's the problem but I don't know how to fix it. If I add console.log
into func
like this:
const func = () => {
if (sum >= 10) return;
setTimeout(() => {
getRandNum();
console.log(array, sum);
func();
}, 500);
};
It always logs the same numbers: [1,2,3] 6
. So even though array and sum are changing, function keeps calling itself with same values and it does not stop.