I have one question regarding to my customized useCallBack
that I really have no idea how I should fix it. Under my hook useValueChange
, I use one local variable prevValue
to store the state of input value from hook. the logic is if prevValue
object does not match with updateValue object. go to the if/else logic and then update prevValue
. The issue I have are
- useCallBack block still run even
JSON.stringify(updateValue)
does not change - setPrevValue does not update
prevValue
right away. as useState runs asyncso wheneve I call the hook multiple time even updateValue does not change, the apicallupdateValueApiCall
trigger consistentlyany idea how I should fix?
function useValueChange(updatedValue) { const [prevValue, setPrevValue] = useState<ValueQueryVariables>({name: '', address: '', info:{a: '', b''}}); const onValueChange = useCallback(async (): Promise<void> => { const isValueUpdate = !isEqual(prevValue, updateValue); if (isValueUpdate) { console.log({updatedValue, prevValue}); setPrevValue(() => updatedValue); await updateValueApiCall({...updatedValue}); } }, [JSON.stringify(updateValue)]); return {onValueChange};}