Drawer navigation doesn't update component like Stack navigation does

Viewed 839

When I work with Stack navigation the components are "refreshed" it does the useEffect action correctly, in the case of when I use Drawer navigation it updates only once, I leave one screen and enter another and return to the first one and the useEffect is not executed again , which if the Stack navigation does it perfectly. Could someone guide me?

I don't speak english, sorry my writing

1 Answers

This is because you need to use an navigation.addListener subscription in your effect hook with the 'focus' event to listen to.

https://reactnavigation.org/docs/navigation-events/#navigationaddlistener

Here is a App.js standalone demo (started on a blank expo init project ) :

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { createDrawerNavigator } from "@react-navigation/drawer";
import { NavigationContainer } from "@react-navigation/native";

const Drawer = createDrawerNavigator();

function MyDrawer() {
  return (
    <Drawer.Navigator>
      <Drawer.Screen name="Feed" component={Feed} />
      <Drawer.Screen name="Article" component={Article} />
    </Drawer.Navigator>
  );
}

function Feed({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      // do something
      console.log("feed is focused");
    });

    return unsubscribe;
  }, [navigation]);

  return (
    <View style={styles.container}>
      <Text>Feed</Text>
    </View>
  );
}

function Article({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      // do something
      console.log("article is focused");
    });

    return unsubscribe;
  }, [navigation]);

  return (
    <View style={styles.container}>
      <Text>Article</Text>
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <MyDrawer />
    </NavigationContainer>
  );
}

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