React hooks: accessing up-to-date state from within a callback

后端 未结 8 1767
梦谈多话
梦谈多话 2020-12-25 09:35

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

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-25 10:28

    Update Dec 2020:

    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:

    • https://www.npmjs.com/package/react-usestateref

    Original Answer

    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.
    })
    

提交回复
热议问题