简体   繁体   中英

React native useEffect clean up not using the updated states properly

I have been scratching my head on something weird that happens during the clean up function of useEffect. Basically, in the clean up code, I invoke a updateStore() function to update store based on the boolean value of changeFlag. However, the updateStore() and even the clean up function itself is not reflecting the updated state of changeFlag and I could not figure out why.

I tried to do a simple POC on a clean project thinking that it might be caused by some bug of my project but it is still having the same problem.

App.js

import React, {useState, useEffect} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';



const Test = ({navigation}) => {
  //const { id } = route.params;
  const [changeFlag, setChangeFlag] = useState(false);
  useEffect(() => {
      console.log(`Start: ${changeFlag}`);
      return function cleanup () {
          console.log(`Exiting: ${changeFlag}`);
          updateStore();
      };
  }, []);

  useEffect(() => {
    console.log(`Flag changed! ${changeFlag}`);
  }) 

  const toggle = () => {
      setChangeFlag(!changeFlag);
  }

  const updateStore = () => {
    console.log(`Print flag ${changeFlag}`);
  }

  return (
      <View style={styles.container}>
          <Text>{changeFlag ? "True" : "False"} </Text>
          <Button title={"Press toggle"} onPress={toggle}/>
      </View>
  );
}

const Home = ({navigation}) => {
  return(
    <View>
      <Button title={"Go Test"} onPress={() => navigation.navigate('Test')}/>
    </View>
  );
}

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Test" component={Test} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App

Output

Start: false
Flag changed! false
Flag changed! true
Exiting: false
Print flag false

Thanks in advance!

If you want to have access to the new value of changeFlag in useEffect you need to put it in the [] at the end of the useEffect , by doing this you're saying the useEffect to keep track of the updated value

useEffect(() => {
  console.log(`Start: ${changeFlag}`);
  return function cleanup () {
      console.log(`Exiting: ${changeFlag}`);
      updateStore();
  };
}, [changeFlag]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM