Search code examples
reactjsreact-componentreact-state

how does a onChange handler get access to the previous state of variables?


i found following example somewhere and I cannot figure out how it is supposed to work, can someone explain it please, I understand the usage of setState and initializing it, but I don't understand the variable prevInputData! what is calling the setInputData and how the previous state is being passed as parameter when setInputData is being called, i'm so confused!

    //state stuff 
    const [inputData, setInputData] = useState({firstName: "", lastName: ""})

    //onChange handler 
    function handleChange(event) {
      const {name, value} = event.target

      setInputData(prevInputData => { //HOW THIS IS SUPPOSED TO WORK?
        return {
            ...prevInputData,
            [name]: value
          }
       });
    }

    //form input 
    <input name="lastName" 
           value={inputData.lastName}
           onChange={handleChange}
    />

Solution

  • This is kind of misleading. It's not actually the state value from the previous render cycle, it's the current state value being passed as an argument to the functional state update callback. By the time the callback is invoked though, during reconciliation, to update state, it is now the state from the last render cycle, and returns the next state value.

    Functional Updates

    setInputData(prevInputData => { // actually current state when queued
      return {
        ...prevInputData,
        [name]: value
      }
    });