I was experiencing some weird behavior in my React app, where setEffect with a state (say state1) as a second argument was changing another variable (not a state) without setState1 being ever called. So I made the following code to see if the same would happen, and it did:
import React, { useState, useEffect } from 'react';
function App() {
let [state1, setState1] = useState('');
let count = 0;
useEffect(() => {
count = count + 1000;
console.log('USEEFFECT_count: ' + count);
}, [state1]);
setInterval(() => {
console.log('SETINTERVAL_count: ' + count);
}, 1000);
return (
<div className="App">
</div>
);
}
export default App;
Basically, the variable count should receive the value of 1000 only when setState1 is called (which never happens) to change the value of state1. But the return of the console is
SETINTERVAL_count: 1000
SETINTERVAL_count: 0
SETINTERVAL_count: 1000
SETINTERVAL_count: 0
SETINTERVAL_count: 1000
SETINTERVAL_count: 0
SETINTERVAL_count: 1000
SETINTERVAL_count: 0
SETINTERVAL_count: 1000
SETINTERVAL_count: 0
And the console.log inside the useEffect is never called, as expected. But if that's the case, then:
- why is he summing 1000 to count ?
- why is this value resetting to 0 ?
If I add a state2 and another useEffect that sums 5000 to count, it adds to the 1000 from the first useEffect :
import React, { useState, useEffect } from 'react';
function App() {
let [state1, setState1] = useState('');
let [state2, setState2] = useState('');
let count = 0;
useEffect(() => {
count = count + 1000;
console.log('USEEFFECT1_count: ' + count);
}, [state1]);
useEffect(() => {
count = count + 5000;
console.log('USEEFFECT2_count: ' + count);
}, [state2]);
setInterval(() => {
console.log('SETINTERVAL_count: ' + count);
}, 1000);
return (
<div className="App">
</div>
);
}
export default App;
The result of the console.log:
SETINTERVAL_count: 6000
SETINTERVAL_count: 0
SETINTERVAL_count: 6000
SETINTERVAL_count: 0
SETINTERVAL_count: 6000
SETINTERVAL_count: 0
SETINTERVAL_count: 6000
SETINTERVAL_count: 0