When component A passes a callback to external js lib, and before external lib calls the callback the component gets updated, and you are accessing the value from state. The callback will have the old value, as it is not running in the current context and because that you will get stale values. So, to get the current value, you need to wrap your callback in below custom hook. It will allow you to access the current value of your state. I had experienced this issue in functional components, and I think bind will solve the problem in class components.
const useWrap = (func: (...funcArgs: any) => void) => {
const [args, setArgs] = useState(null);
const [funcExecuted, setFuncExecuted] = useState(false);
useEffect(() => {
if (funcExecuted) {
if (!!args) {
func(...args);
} else {
func();
}
}
args && setArgs(null);
funcExecuted && setFuncExecuted(false);
}, [funcExecuted]);
return (...callbackArgs) => {
setArgs(callbackArgs);
setFuncExecuted(true);
};
};
Use it wisely. As in some cases, it may cause problems.