I am calling a function that uses state but the state that is being used in function is old state even though if you use the react debugger on chrome it displays new state.
const [somevalue,setsomevalue] = useState("newstate")
function myfunction()
{
console.log(somevalue)
}
myfunction()
output:
oldstate
I was thinking of using forceUpdate() but I am using classless component.
const CauseCodeChangeHandler = (e) => {
setSelectedCauseCode(e.target.value);
};
const serQtyChangeHandler = (e) =>
{
if (SelectedCauseCode == "CUS")
{
}
else if (SelectedCauseCode == "OPS")
{
}
else if (SelectedCauseCode == 'OOW')
{
}
}
my component:
<ServiceSelectInput changeHandler={CauseCodeChangeHandler}/>
It is using old CauseCode not one that I just selected.
This is the stale closure problem and is something that useCallback is designed to address:
import {useCallback, useState} from 'react';
function Component () {
const [someValue, setSomeValue] = useState('newstate');
// This will make sure that `myFunction` is recreated
// every time that `someValue` changes
const myFunction = useCallback(() => console.log(someValue), [someValue]);
// ...rest of component
}