Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why react returns same value in every increment?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading