0

I have created a custom hook with callback to use it as setState in Class Component. But it is showing unexpected behaviour.

import {useState, useEffect, useRef, useCallback} from 'react'

export function useStateWithCallback(initialState:any) {
    const [state, setState] = useState(initialState);
    const callbackRef:any = useRef(null);
    
    const dispatchAction = useCallback((obj:any, callback:any)=>{
        callbackRef.current = callback;
        setState(obj);
    },[]);

    useEffect(()=>{
        if(callbackRef.current){
            callbackRef.current(state);
            callbackRef.current = null;
        }
    },[state]);

    return [state, dispatchAction];
}

usage of this hook

const [orderId, setOrderId] = useStateWithCallback(0);

const postOrder = useCallback(()=>{

//After successfully posted order

  setOrderId(ordId, (newOrdId:string)=>{
     console.log('newOrdId: '+newOrdId);
     console.log('orderId: '+orderId);
  });

},[]);

what I get in console is displayed below:

newOrdId: 8438247

orderId: 0

Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
  • Ref: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Yoshi Oct 05 '21 at 11:25
  • Please describe the *"unexpected behaviour"*. If it's the fact that `orderId` does not match `newOrdId`, then refer to the link above. – Yoshi Oct 05 '21 at 11:27

0 Answers0