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

React useState does update in dev tools but not in the console

Hey i have this function

   const [mouseIsDown, setMouseDown] = useState(true);

   function handleMouseUp() {
        console.log('mouseUp')
        console.log(mouseIsDown)
        setMouseDown(false);
        setInterval(() => {
            console.log(mouseIsDown)
        }, 1000)

    }

and when it is trigged it logs:

- mouseUp
- true
- true
- true
- true
- true
...

But the react dev tools show that mouseIsDown is actually false, but when i log its value in a interval it still logs true when i set the value of mouseIsDown to false.

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

I have no idea why its like that, any help is welcome 😀

>Solution :

The reason is this line

setInterval(() => {
     console.log(mouseIsDown)
}, 1000)

when you use interval like that, the inside of the function is like a "snapshot" of current state. this is why you always get the starting mouseIsDown value.

in order to fix this, you need to use useRef as a reference value, so this will save the current state inside of the interval.

new code:

const [mouseIsDown, setMouseDown] = useState(true);
const mouseIsDownRef = useRef();
mouseIsDownRef.current = mouseIsDown; //this will set the current value

function handleMouseUp() {
        console.log('mouseUp')
        console.log(mouseIsDown)
        setMouseDown(false);
        setInterval(() => {
            console.log(mouseIsDownRef?.current)
        }, 1000)

    }
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