'Function never uses updated state
In the sample component below, myFunc's state1 is never updated while the console.log in the useEffect outputs the updated state correctly. What could be the reason for this?
const TestComponent = () => {
const [state1, setState1] = useState();
useEffect(() => {
console.log(state1);
}, [state1]);
const myFunc(() => {
const newState1 = getNewState1();
console.log(state1); // never outputs updated state, even when myFunc is called multiple times
if (state1 !== newState1) {
console.log('updated state');
setState1(newState1);
}
});
}
Obviously, my real component is much more complicated, but the only time setState1 is called is in myFunc which is confirmed by the useEffect.
Edit:
const TestComponent2 = () => {
useFocusEffect(
useCallback(() => {
myFunc();
}),
);
};
I am trying to call myFunc when TextComponent2 is focused/loaded. I realize that useEffect with no dependencies may be the best option here. Thanks!
Solution 1:[1]
I was using useCallback with no relevant dependencies which most likely caused state1 to be the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hyrial |
