EDIT (22 June 2020): as this question has some renewed interest, I realise there may be a few points of confusion. So I would like to highlight: the example in the question
To solve exactly this issue I have created a react module for that. react-usestateref (Reacrt useStateRef). E.g. of use:
var [state,setState,ref]=useStateRef(0)
It's works exaclty like useState but in addition, it gives you the current state under ref.current
Learn more:
You can get the latest value by using the setState
For e.g.
var [state,setState]=useState(defaultValue)
useEffect(()=>{
var updatedState
setState(currentState=>{ // Do not change the state by get the updated state
updateState=currentState
return currentState
})
alert(updateState) // the current state.
})