useFocusEffect doesn't update setstate

Viewed 983

I'm trying to use useFocusEffect to setState. but I can't update state...

How can i fix this?

const [isFocuse, setIsFocuse] = useState(true);

  useFocusEffect(
      React.useCallback(() => {
        setIsFocuse('sample1');
        console.log('mount', isFocuse); // mount true
        return () => {
          setIsFocuse('sample2');
          console.log('unmount', isFocuse); // unmount true
        };
      }, []),
  );
1 Answers

I know its a old question but for anyone looking for solution. According to React navigation docs on useFocusEffect. You need to add state you need to change as a dependency to your useCallback hook. So correct code will be. `

   const [isFocuse, setIsFocuse] = useState(true);
       useFocusEffect(
           React.useCallback(() => {
               setIsFocuse('sample1');
               console.log('mount', isFocuse); 
               return () => {
                   setIsFocuse('sample2');
                   console.log('unmount', isFocuse); 
               };
  }, [isFocuse]));`

And that will work.

PS- setState or its hooks equivalent is async task so console.log() may run before state is updated will result is incorrect values of log in this case. You can use useEffect hook as with isFocuse as dependency to log the change in state

Related