Home > Back-end >  React useState does update in dev tools but not in the console
React useState does update in dev tools but not in the console

Time:03-20

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.

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

CodePudding user response:

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)

    }
  • Related