
Adding Listener to Drawer Navigator Routes
Unlike stack navigators, screens of drawer navigators are not destroyed and recreated, when the user close and re-opens these screens. These may cause some problems like the data is not updated although the component is rendered. These kind of problems can be solved by adding listeners to the routes of drawer navigators.
We can illustrate this situation with a simple example. Suppose ScreenA and ScreenB are the route components of your drawer navigator. Each component has a counter value initialized to 0, and a function that increments the counter value by 1. While ScreenA calls this function in its body part, ScreenB calls it when it is focused which is achieved by adding a navigation listener.
When we navigate between these screens of drawer navigator, while counter value remains the same in ScreenA, increment function runs on ScreenB thanks to listener.
MainNavigator.js
ScreenA.js
ScreenB.js
the output when we navigate from ScreenA to ScreenB, and again to ScreenA mutliple times:
Screen A counter is 1
Screen B counter is 0
Screen B counter is 1
Screen B counter is 2
You can download and try the example from the following link: