I’v written the code below but always return 0. Why?
const [inc, setInc] = useState(0);
useEffect(() => {
const ti = setInterval(() => {
setInc(prevState => prevState + 1);
console.log(inc);
}, 3000)
return () => {
clearInterval(ti);
}
}, []);
>Solution :
inc is assigned a value at the top of the component. It doesn’t change until the component re-renders.
Your useEffect runs the function you pass to it once (because the dependency list is []). That function closes over the value of inc during the first render.
Every time setInterval triggers the function you pass to it, it sees that closed over value of the original inc.
The updated values are only available in:
- The re-rendered component
- The callback function you pass to
setInc
So log it during the re-render of the component instead of inside the interval. You can use a second effect hook to log it only when it changes.
const [inc, setInc] = useState(0);
useEffect(() => {
const ti = setInterval(() => {
setInc(prevState => prevState + 1);
}, 3000)
return () => {
clearInterval(ti);
}
}, []);
useEffect(() => {
console.log(inc);
}, [inc]);