I have been experimenting with setInterval
. Both the codes were executed in Chrome. Below is my react component
function App() {
let [value, setValue] = useState(0);
useEffect(() => {
const id = setInterval(() => console.log(value), 1000);
return () => clearInterval(id);
}, []);
return (
<div className="App">
<p>{value}</p>
<button onClick={() => setValue(value 1)}> </button>
<button onClick={() => setValue(value - 1)}>-</button>
</div>
);
}
The console.log
in setTimeout
inside useEffect
keeps printing 0
no matter how many times you increment or decrement the value via button click.
Following code is being executed in browser (Chrome) console
let value = 0;
setInterval(() => console.log(value), 1000);
value = 3; // can be considered as setValue (sort of)
Now the browser console prints 3
which is expected.
I wonder why there is a difference in behaviour and would appreciate if someone could point out the reason for this. Any other code snippet or link that demonstrate this even better would be great.
CodePudding user response:
You need to pass value
as a dependency to your useEffect. Unless you give the list of items that your effect dependent upon in the dependency array, it will keep using the initial value
.
useEffect(() => {
const id = setInterval(() => console.log(value), 1000);
return () => clearInterval(id);
}, [value]);
CodePudding user response:
İn your example useEffect only work once when page loaded. This is why you only get console.log(0). If you want to make it when value change you need specify that in useEffect
For example
UseEffect(() =>{ console.log(value) }, [value])
In your example when you click to button, first value sets after that useEffect works and setInternals function triggered after 1s.