How can I use useRef to reset state when it is re-rendering?

43 Views Asked by At

I need to store a reference of an old state so I can use it in case the new state is not valid. How can I do this with useRef? The issue is that the component re-renders and re-initializes state with each character input since it is a datepicker. What is the best way to do this?

I tried local storage, but I cannot store the functionality of state since localstorage only stores strings.

const state:DateRangePickerState = {DateRange, with functionality}

  function checkDateValidity(state: DateRangePickerState) {
    let isValid: Boolean = {check for validity}
    return isValid
  }

  if (!checkDateValidity(state)) {
    state.setValue(oldState) // <---{use oldState Ref}

    }
  }
  else {
    let oldState = useRef(state.value) //<---but the oldState value is initialized here
  }
0

There are 0 best solutions below