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