'REACT being able to see immediately the state changed using a useRef hook only inside callbacks. not inside other functions

I have prepared a simple example to show you guys what is my problem. I declare these variables :

const [probeState, setProbeState] = useState(0);
const probeRef = useRef();
probeRef.current = probeState;

now If I call this code :

console.log(probeRef.current)
setProbeState(1);
console.log(probeRef.current)

inside a callback function of a konva component for example, the output will be :

0
1

instead if I call it inside an useEffect or any other function the output will be :

0
0

this is an example of the first case inside of a callback function : parent component return :

<Path
   key={"previewPath"+pathKey}
   pathKey={pathKey}
   handlePathMouseDown = {handlePathMouseDown}
/>

the component Path :

return (
    
      <Shape
        key={"pathLine"+pathKey}
        stroke={strokeColor}
        onMouseDown={()=> {
         
          handlePathMouseDown(pathKey);
       
        }}
/>

the callback function:

const handlePathMouseDown = useCallback((pathKey) => {      
      console.log(probeRef.current)
      setProbeState(1);
      console.log(probeRef.current)
      
    },[]);

from my personal understandings in theory the output should always be the second because the state will be updated on the next re-render right? So could you please explain me why is this happening? Thanks a lot!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source