Home > Enterprise >  Function never uses updated state
Function never uses updated state

Time:01-29

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!

CodePudding user response:

I was using useCallback with no relevant dependencies which most likely caused state1 to be the same.

CodePudding user response:

I think if u change font and colour it may work more effectively

  •  Tags:  
  • Related